Skip to content
Laviyx Learn

Try

Node.js Core Practice

Practise Node.js core modules with real scripts. Files, JSON, paths, URLs, command-line arguments, events, streams and asynchronous code. Every solution has been run with Node.js and shows its real output.

Beginner7 problemsUpdated

Review first: Working with Files (fs), Paths and URLs, Process, Arguments and Environment Variables, Events and EventEmitter, Streams, Asynchronous Node and the Event Loop

  1. 1.Sales report from a JSON file

    Beginner

    Write sales.json containing [{"day":"Mon","amount":4200},{"day":"Tue","amount":3800},{"day":"Wed","amount":5100}] using writeFile, read it back, and print the total, the best day and the average (rounded to a whole number).

    Show hint

    JSON.stringify before writing, JSON.parse after reading, then reduce for the total and a loop or reduce for the best day.

    Show solution
    JavaScript
    import { readFile, writeFile } from "node:fs/promises";
    
    await writeFile("sales.json", JSON.stringify([
      { day: "Mon", amount: 4200 },
      { day: "Tue", amount: 3800 },
      { day: "Wed", amount: 5100 },
    ]));
    const sales = JSON.parse(await readFile("sales.json", "utf8"));
    const total = sales.reduce((sum, s) => sum + s.amount, 0);
    const best = sales.reduce((a, b) => (b.amount > a.amount ? b : a));
    console.log("Total:", total);
    console.log("Best day:", best.day, best.amount);
    console.log("Average:", Math.round(total / sales.length));
    Output
    Total: 13100
    Best day: Wed 5100
    Average: 4367
  2. 2.Default settings when a file is missing

    Beginner

    Write a function loadConfig(file) that returns the parsed JSON from the file, or { "theme": "light" } if the file does not exist, and re-throws any other error. Call it with a file that does not exist and print the result.

    Show hint

    Catch the error and check err.code === "ENOENT".

    Show solution
    JavaScript
    import { readFile } from "node:fs/promises";
    
    async function loadConfig(file) {
      try {
        return JSON.parse(await readFile(file, "utf8"));
      } catch (err) {
        if (err.code === "ENOENT") return { theme: "light" };
        throw err;
      }
    }
    
    console.log(await loadConfig("no-such-config.json"));
    Output
    { theme: 'light' }
  3. 3.Group files by extension

    Beginner

    Given the file names ["report.PDF", "photo.jpg", "notes.txt", "scan.pdf", "logo.png", "README"], group them by lower-cased extension (use "(none)" for files without one) and print the groups as an object.

    Show hint

    path.extname(name).toLowerCase() || "(none)", then add each name to groups[ext].

    Show solution
    JavaScript
    import path from "node:path";
    
    const files = ["report.PDF", "photo.jpg", "notes.txt", "scan.pdf", "logo.png", "README"];
    const groups = {};
    for (const name of files) {
      const ext = path.extname(name).toLowerCase() || "(none)";
      (groups[ext] ??= []).push(name);
    }
    console.log(groups);
    Output
    {
      '.pdf': [ 'report.PDF', 'scan.pdf' ],
      '.jpg': [ 'photo.jpg' ],
      '.txt': [ 'notes.txt' ],
      '.png': [ 'logo.png' ],
      '(none)': [ 'README' ]
    }
  4. 4.Read tracking parameters from a URL

    Beginner

    From the URL https://shop.example.com/sale?utm_source=newsletter&utm_medium=email&item=42, print every parameter whose name starts with utm_, and then the URL without those parameters.

    Show hint

    Loop over url.searchParams, collect the utm_ keys, then delete them with searchParams.delete.

    Show solution
    JavaScript
    const url = new URL("https://shop.example.com/sale?utm_source=newsletter&utm_medium=email&item=42");
    const utmKeys = [...url.searchParams.keys()].filter((key) => key.startsWith("utm_"));
    for (const key of utmKeys) console.log(key, "=", url.searchParams.get(key));
    for (const key of utmKeys) url.searchParams.delete(key);
    console.log(url.href);
    Output
    utm_source = newsletter
    utm_medium = email
    https://shop.example.com/sale?item=42
  5. 5.Order events with EventEmitter

    Intermediate

    Create an EventEmitter called orders. Listen for placed (print the order id and total) and shipped (print the id and courier). Emit one placed and one shipped event, then print how many listeners placed has.

    Show hint

    orders.on("placed", (order) => ...), orders.emit("placed", { id: 7, total: 999 }), orders.listenerCount("placed").

    Show solution
    JavaScript
    import { EventEmitter } from "node:events";
    
    const orders = new EventEmitter();
    orders.on("placed", (order) => console.log(`Order ${order.id} placed: ₹${order.total}`));
    orders.on("shipped", (id, courier) => console.log(`Order ${id} shipped with ${courier}`));
    
    orders.emit("placed", { id: 7, total: 999 });
    orders.emit("shipped", 7, "BlueDart");
    console.log("placed listeners:", orders.listenerCount("placed"));
    Output
    Order 7 placed: ₹999
    Order 7 shipped with BlueDart
    placed listeners: 1
  6. 6.Total a CSV file line by line

    Intermediate

    Write a CSV file expenses.csv with a header category,amount and the rows food,450, travel,1200, food,300 and rent,8000. Then read it line by line with readline, skipping the header, and print the total per category.

    Show hint

    Use createInterface({ input: createReadStream("expenses.csv") }) and for await (const line of rl); split each line on the comma.

    Show solution
    JavaScript
    import { createReadStream } from "node:fs";
    import { writeFile } from "node:fs/promises";
    import { createInterface } from "node:readline";
    
    await writeFile("expenses.csv", "category,amount\nfood,450\ntravel,1200\nfood,300\nrent,8000\n");
    
    const totals = {};
    let header = true;
    for await (const line of createInterface({ input: createReadStream("expenses.csv"), crlfDelay: Infinity })) {
      if (header) { header = false; continue; }
      const [category, amount] = line.split(",");
      totals[category] = (totals[category] ?? 0) + Number(amount);
    }
    console.log(totals);
    Output
    { food: 750, travel: 1200, rent: 8000 }
  7. 7.Run tasks in parallel

    Intermediate

    Three simulated API calls take 300, 200 and 100 ms and return "prices", "stock" and "reviews". Run them in parallel with Promise.all, print the results in their original order, and print whether the whole thing took less than 450 ms.

    Show hint

    Make a wait(ms, value) helper that returns a promise resolving after ms, and measure with Date.now() before and after.

    Show solution
    JavaScript
    const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
    
    const start = Date.now();
    const results = await Promise.all([wait(300, "prices"), wait(200, "stock"), wait(100, "reviews")]);
    console.log(results);
    console.log("Under 450 ms:", Date.now() - start < 450);
    Output
    [ 'prices', 'stock', 'reviews' ]
    Under 450 ms: true