Skip to content
Tutorials Center
My learning

Topics

Lesson 131 of 133 ยท Practice and Review

Practice Problems: Core Node

16 graded Node.js exercises with hints and verified solutions on paths, URLs, modules, files, events, buffers and timers. Run each one in your browser and compare.

Reading about Node.js teaches you what exists. Writing code teaches you what to reach for. This page has 16 exercises on the core of the platform: paths and URLs, modules, files and folders, events, buffers and encodings, and timers. They start with one-liners and end with a small binary protocol, and each one is a real task that comes up in everyday work.

Every exercise has a short task, an editor with starter code, and a hidden solution. The starter code runs as given: the function you must write is a stub that returns a placeholder, and the comment at the bottom shows the exact output the program prints once your code is right. Replace the stub, press Run, and compare your output with the comment.

  • Try first, peek later. Give each exercise a real attempt before you open the solution. Being stuck for a few minutes is where the learning happens.
  • Compare, don't copy. Your solution can look different from ours and still be correct. Read ours for ideas, then improve yours.
  • Read the error. Node prints the file, the line and the error code. Treat each message as a hint, and look at error.code before the text.
  • Test the edges. Empty input, a missing file, a name with several dots or an emoji in a string are where programs break. Most exercises include such a case.

The editor runs Node.js 24 as an ES module, so import and top-level await work. Files you create live only for one run, in a folder of their own, and nothing leaves the editor. Keep the cheat sheet open in another tab, and continue with Practice Problems: Streams, HTTP and Concurrency when you are ready for the harder ones.

Modules, paths, URLs and util

These practice path and os, URL, ES modules and the util module.

1. Change a file extension (Beginner)

Write changeExtension(file, newExtension). It returns the same path with the extension replaced ('/docs/report.txt' and '.md' give '/docs/report.md'). Keep the folder and the base name, and do not break names with several dots such as archive.tar.gz, where only the last extension is replaced. Use the path module, not string slicing.

Node.js Exercise 1: Change a file extension

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Show solution
NODE
  const { dir, name } = path.parse(file);
  return path.join(dir, name + newExtension);

path.parse splits a path into dir, name and ext, and ext is only the part after the last dot, so archive.tar.gz keeps archive.tar as its name. A file without an extension (Makefile) simply gets one. path.join skips an empty dir (the second and third cases print a relative path, the others an absolute one). Joining with + on a slash would be wrong on Windows, which is why we use the module.

2. Read a query string (Beginner)

Write parseQuery(address). It takes a full URL and returns a plain object of its query parameters. A name that appears once gives a string, and a name that appears several times gives an array of strings in order. Use URL and searchParams.

Node.js Exercise 2: Read a query string

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Show solution
NODE
  const result = {};
  for (const [name, value] of new URL(address).searchParams) {
    if (!(name in result)) {
      result[name] = value;
    } else if (Array.isArray(result[name])) {
      result[name].push(value);
    } else {
      result[name] = [result[name], value];
    }
  }
  return result;

Iterating searchParams yields [name, value] pairs, already decoded (blue+shirt becomes blue shirt). The first occurrence stores a string, and the second turns it into an array. Note that every value is a string: page is '2', not the number 2. A hostile query could use a name such as __proto__; for untrusted input create the result with Object.create(null) or use a Map.

3. Write a module and import it (Intermediate)

Write loadGreeter(). It must create a file greeter.mjs in the current folder whose source exports a named function greet(name) (returns Hello, NAME!) and a default export that is the number of times greet is allowed to be used (3). Then it imports the file with a dynamic import() and returns the module object. Imports of relative files are resolved against the importing file, and the editor runs your program from the same folder, so ./greeter.mjs works.

Node.js Exercise 3: Write a module and import it

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Show solution
NODE
  const source = [
    'export function greet(name) {',
    '  return `Hello, ${name}!`;',
    '}',
    'export default 3;',
    '',
  ].join('\n');
  await writeFile('greeter.mjs', source);
  return import('./greeter.mjs');

An ES module namespace object has one key per export, and the default export lives under the key default, which is why Object.keys shows both default and greet. import() returns a promise and works in any file, even from CommonJS. The module is cached by URL: if you rewrite greeter.mjs and import it again in the same run you get the old version, and a query string such as ./greeter.mjs?v=2 creates a new cache entry.

4. Parse command-line options (Intermediate)

Write parseCli(args) with util.parseArgs. Supported options: --port (string, default '3000'), --verbose or -v (boolean), and --tag which may be given several times (an array of strings). Positional arguments are allowed. Return { port, verbose, tags, files } where port is a number.

Node.js Exercise 4: Parse command-line options

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Show solution
NODE
  const { values, positionals } = parseArgs({
    args,
    allowPositionals: true,
    options: {
      port: { type: 'string', default: '3000' },
      verbose: { type: 'boolean', short: 'v', default: false },
      tag: { type: 'string', multiple: true, default: [] },
    },
  });
  return { port: Number(values.port), verbose: values.verbose, tags: values.tag, files: positionals };

Without args, parseArgs reads process.argv.slice(2); passing an array makes the function testable. multiple: true collects repeated options into an array. Unknown options throw an error with the code ERR_PARSE_ARGS_UNKNOWN_OPTION (strict mode is the default), which is what you want in a command-line tool: a typo should fail loudly.

Files and folders

These practice fs promises, directories and paths and permissions.

5. Count lines and words (Beginner)

Write countFile(file). It reads a text file and returns { lines, words }. Count lines as the number of non-empty lines, and words as the number of runs of non-space characters. The program creates the file for you.

Node.js Exercise 5: Count lines and words

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Show solution
NODE
  const text = await readFile(file, 'utf8');
  const lines = text.split('\n').filter((line) => line.trim() !== '');
  const words = text.split(/\s+/).filter(Boolean);
  return { lines: lines.length, words: words.length };

split('\n') on a text that ends with a newline produces an empty last item, and blank lines in the middle produce more, so filtering is needed. For words, split(/\s+/) produces an empty string at the start or end when the text begins or ends with whitespace, and filter(Boolean) removes it. For files too big for memory, read them as a stream instead (see file streams).

6. Size of a folder (Intermediate)

Write folderSize(folder). It returns the total number of bytes in all regular files inside the folder and its subfolders. The program builds a small tree with known file sizes.

Node.js Exercise 6: Size of a folder

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Show solution
NODE
  let total = 0;
  const entries = await readdir(folder, { withFileTypes: true, recursive: true });
  for (const entry of entries) {
    if (entry.isFile()) {
      total += (await stat(path.join(entry.parentPath, entry.name))).size;
    }
  }
  return total;

With recursive: true one readdir call returns every entry in the tree, and entry.parentPath tells you the folder it lives in (Node 20.12 and newer). Only isFile() entries have a size worth adding; folders themselves are skipped. If a file could disappear while you work, wrap the stat call and ignore ENOENT, as in the directory snapshot project. A recursive function with Promise.all over the entries is the older alternative.

7. Update a JSON file safely (Intermediate)

Write updateJson(file, patch). It reads a JSON file, merges the patch object into it (top-level keys only), and writes it back. To avoid a half-written file if the program stops in the middle, write to a temporary file first and then rename it over the original. Return the new object.

Node.js Exercise 7: Update a JSON file safely

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Show solution
NODE
  const current = JSON.parse(await readFile(file, 'utf8'));
  const updated = { ...current, ...patch };
  const temporary = `${file}.tmp`;
  await writeFile(temporary, JSON.stringify(updated, null, 2));
  await rename(temporary, file);
  return updated;

On the same file system rename replaces the target atomically: a reader sees either the old file or the new one, never half of each. Plain writeFile on the real file truncates it first, so a crash during the write loses data. In a real program give the temporary file a unique name (two updates at once would collide on .tmp) and serialize concurrent updates, because two read-modify-write cycles can overwrite each other.

Events

These practice events, abort signals and errors.

8. A counter that emits events (Beginner)

Complete the class Counter, which extends EventEmitter. increment() adds 1 and emits 'change' with the new value. When the value reaches the limit given to the constructor, it also emits 'limit' once, and further increments do nothing (and emit nothing).

Node.js Exercise 8: A counter that emits events

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Show solution
NODE
    if (this.value >= this.limit) {
      return;
    }
    this.value++;
    this.emit('change', this.value);
    if (this.value === this.limit) {
      this.emit('limit');
    }

emit calls the listeners synchronously, in the order they were added, before it returns. Guarding at the top keeps the later increments silent. Subclassing EventEmitter is fine for small classes; many teams prefer composition (a private emitter field) so that emit is not part of the public interface.

9. Wait for an event, with a time limit (Intermediate)

Write waitFor(emitter, eventName, ms). It returns a promise that resolves with the array of arguments of the first matching event, or rejects with an Error whose message is timed out waiting for NAME when ms milliseconds pass first. Clean up: the timer must be cleared and the listener removed in both cases.

Node.js Exercise 9: Wait for an event, with a time limit

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Show solution
NODE
  return new Promise((resolve, reject) => {
    const onEvent = (...args) => {
      clearTimeout(timer);
      resolve(args);
    };
    const timer = setTimeout(() => {
      emitter.off(eventName, onEvent);
      reject(new Error(`timed out waiting for ${eventName}`));
    }, ms);
    emitter.once(eventName, onEvent);
  });

This is events.once with a deadline. A listener that is never removed after a timeout is a classic leak: every call adds one, and Node warns about more than 10 listeners on one event. The built-in once(emitter, name, { signal: AbortSignal.timeout(ms) }) does the same cleanup for you and rejects with an AbortError; writing it by hand once shows what it does.

10. A tiny event emitter (Intermediate)

Without using node:events, write createEmitter() returning { on, off, once, emit }. on(name, fn) registers a listener and returns a function that removes it. off(name, fn) removes one. once registers a listener that runs at most once. emit(name, ...args) calls the listeners in registration order and returns true if there was at least one. A listener that removes itself or others while emit is running must not break the loop.

Node.js Exercise 10: A tiny event emitter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Show solution
NODE
  const listeners = new Map();

  function off(name, fn) {
    const list = listeners.get(name);
    if (list) {
      listeners.set(name, list.filter((item) => item !== fn));
    }
  }

  function on(name, fn) {
    listeners.set(name, [...(listeners.get(name) ?? []), fn]);
    return () => off(name, fn);
  }

  function once(name, fn) {
    const wrapper = (...args) => {
      off(name, wrapper);
      fn(...args);
    };
    return on(name, wrapper);
  }

  function emit(name, ...args) {
    const list = listeners.get(name) ?? [];
    for (const fn of [...list]) {
      fn(...args);
    }
    return list.length > 0;
  }

  return { on, off, once, emit };

emit loops over a copy of the list, so a listener that unsubscribes itself (as once does) cannot make the loop skip the next one. Node's EventEmitter does the same. The second emit('hi', 'Ben') prints only third heard Ben: stop() removed the first listener and the once listener removed itself during the first emit. It still returns true, because one listener is left. This version also leaves out error event handling and the listener limit warning that the real class has.

Buffers and encodings

These practice buffers, typed arrays and text encoding.

11. Characters or bytes? (Beginner)

Write measure(text) returning { characters, codeUnits, bytes }: the number of Unicode characters (code points), the length property (UTF-16 code units) and the number of bytes in UTF-8. The test strings contain accents, a Japanese word and an emoji.

Node.js Exercise 11: Characters or bytes?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Show solution
NODE
  return {
    characters: [...text].length,
    codeUnits: text.length,
    bytes: Buffer.byteLength(text, 'utf8'),
  };

Spreading a string iterates by code point, so an emoji counts once; text.length counts UTF-16 code units, where the emoji takes two (a surrogate pair). UTF-8 needs 1 byte for ASCII, 2 for รฉ, 3 for each Japanese character and 4 for the emoji. Use Buffer.byteLength whenever a protocol or file limit is expressed in bytes, never .length. A "character" a user sees can even be several code points (flags, accents built from combining marks); Intl.Segmenter counts those.

12. Hex dump (Beginner)

Write hexDump(text) that returns the UTF-8 bytes of the text as lowercase hex pairs separated by spaces, and fromHexDump(dump) that turns such a string back into text. Both should handle the empty string.

Node.js Exercise 12: Hex dump

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Show solution
NODE
  return [...Buffer.from(text, 'utf8')].map((byte) => byte.toString(16).padStart(2, '0')).join(' ');

  return Buffer.from(dump.replaceAll(' ', ''), 'hex').toString('utf8');

A Buffer is iterable and yields numbers from 0 to 255. toString(16) loses the leading zero, hence padStart(2, '0'). Going back, Buffer.from(hex, 'hex') expects pairs without spaces; it silently stops at the first invalid character, so validate untrusted input first. For the common case of hex without separators, buffer.toString('hex') does the whole conversion in one call.

13. A length-prefixed message (Advanced)

TCP delivers a stream of bytes with no message boundaries, so protocols often send a length before each message. Write encode(message) returning a Buffer with a 2-byte big-endian length followed by the UTF-8 bytes of the message, and decode(buffer) returning { message, rest }, where rest is the remaining buffer after the first complete message. If the buffer does not hold a complete message yet, decode returns null.

Node.js Exercise 13: A length-prefixed message

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Show solution
NODE
  const body = Buffer.from(message, 'utf8');
  const header = Buffer.alloc(2);
  header.writeUInt16BE(body.length);
  return Buffer.concat([header, body]);

  if (buffer.length < 2) {
    return null;
  }
  const length = buffer.readUInt16BE(0);
  if (buffer.length < 2 + length) {
    return null;
  }
  return {
    message: buffer.subarray(2, 2 + length).toString('utf8'),
    rest: buffer.subarray(2 + length),
  };

The header stores the length in bytes, not characters: the second message has 11 characters but 13 bytes. subarray creates views without copying. Returning null for an incomplete frame is what lets a socket handler keep a growing buffer and try again whenever more data arrives. A real server must also cap the length (a 2-byte header allows up to 65,535, a 4-byte one could ask for 4 GB) and reject larger frames. See binary protocols.

Timers and the event loop

These practice timers, the event loop and promises.

14. Debounce (Intermediate)

Write debounce(fn, ms). It returns a function that waits until ms milliseconds have passed without a new call and then calls fn once, with the arguments of the last call. This is what a search box does so that it does not search on every keystroke.

Node.js Exercise 14: Debounce

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Show solution
NODE
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), ms);
  };

Each call cancels the pending timer and starts a new one, so only the last call in a burst survives. The timer variable lives in the closure, so every debounced function has its own. A variant fires on the first call and ignores the rest for ms (called "leading edge"); throttling is a different tool that allows at most one call per interval.

15. Repeat a few times (Intermediate)

Write repeat(times, ms, fn). It calls fn(round) with round = 1, 2, ... every ms milliseconds (the first call after the first interval), stops after times calls, and returns a promise that resolves when the last call is done. Use setInterval and clean it up with clearInterval.

Node.js Exercise 15: Repeat a few times

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Show solution
NODE
  return new Promise((resolve) => {
    let round = 0;
    const timer = setInterval(() => {
      round++;
      fn(round);
      if (round === times) {
        clearInterval(timer);
        resolve();
      }
    }, ms);
  });

Forgetting clearInterval keeps the process alive forever, because an active interval is work the event loop waits for. Intervals can drift and pile up when the callback is slower than the interval; for work that takes time, prefer a loop with await sleep(ms) between rounds, which waits for each round to finish.

16. Predict the order (Intermediate)

This exercise is about reading, not writing. Predict the order of the six lines the program prints, write it down, and then run the program. The code is complete, there is nothing to fix. Which two lines swap places if you change process.nextTick into queueMicrotask?

Node.js Exercise 16: Predict the order

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Show solution
NODE
// sync, nextTick, promise, immediate, timeout, exit

The callback runs to its end first, so sync comes first. Then Node empties the nextTick queue, then the promise jobs, and then the loop continues: after the poll phase (where the file callback ran) comes the check phase, so immediate runs before the loop returns to the timers phase for timeout. exit fires last, when nothing is left to do. With queueMicrotask instead of process.nextTick, the callback joins the same queue as the promise, in the order queued: promise was queued first, so promise and the replaced line swap places (promise, then microtask).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does path.parse('/a/b/archive.tar.gz').name return?

    The ext is only the part after the last dot (.gz), so the name keeps everything before it, which is archive.tar.
  2. 2. Why does the JSON update exercise write a temporary file and then rename it?

    Writing straight to the real file truncates it first. With a rename, readers see either the complete old file or the complete new one.
  3. 3. What is the UTF-8 byte length of the string "ๆ—ฅๆœฌ่ชž"?

    Each of these Japanese characters needs three bytes in UTF-8, so three characters take nine bytes, while the string length is 3.
  4. 4. Why does emit() in the tiny emitter loop over a copy of the listener list?

    Removing items from an array while iterating it shifts the later items. Iterating over a copy gives every listener that was registered when emit started its turn.
  5. 5. What happens if a program starts a setInterval and never calls clearInterval?

    A pending timer is work the event loop waits for, so the process does not exit until the timer is cleared (or unref'd).

Summary

  • Use path.parse, path.join and URL instead of string slicing: they handle separators, extra dots and encoding for you.
  • A module you write at run time is imported with a dynamic import(), which returns a promise of the module namespace.
  • readdir with { recursive: true, withFileTypes: true } lists a whole tree in one call; update files safely by writing a temporary file and renaming it.
  • Events run listeners synchronously and in order. Always clean up listeners and timers, and iterate over a copy when listeners can change the list.
  • Count bytes with Buffer.byteLength, not .length, and put sizes in front of messages when you send bytes over a stream.
  • Clear every timer you start, and remember that the event loop runs microtasks before timers.

Next: Practice Problems: Streams, HTTP and Concurrency