Node.js Exercises
Time to practise what you've learned. Every exercise has a starter playground that already runs and prints a placeholder result, so you can see the expected format. Replace the TODO parts, run the code, and compare your output with the "Expected" lines. When you're stuck, open the solution — but give it a real try first.
Note: On this site Node examples are simulated. To check your own solution for real, copy it into a file and run
node file.json your computer (Node 22 or newer).
| # | Exercise | Topics |
|---|---|---|
| 1 | Line counter | fs, strings |
| 2 | File extension report | path, objects |
| 3 | Event-driven timer | EventEmitter |
| 4 | Promise pool | async/await, Promise.all |
| 5 | Query-string parser | URL, URLSearchParams |
| 6 | Checksum | crypto, hashes |
| 7 | Uppercase stream | stream.Transform |
| 8 | Tiny JSON API | http, fetch |
1. Line counter
Write countLines(file) that reads a text file and returns { lines, words, chars }, like the Unix wc command. Empty lines count as lines; words are separated by whitespace.
Expected: { lines: 4, words: 8, chars: 39 }
const fs = require('node:fs');
fs.writeFileSync('poem.txt', 'Roses are red\nNode is green\n\nTests pass');
function countLines(file) {
const text = fs.readFileSync(file, 'utf8');
// TODO: compute lines, words and chars
return { lines: 0, words: 0, chars: 0 };
}
console.log(countLines('poem.txt'));
fs.unlinkSync('poem.txt');{ lines: 0, words: 0, chars: 0 }
Show solution
function countLines(file) {
const text = fs.readFileSync(file, 'utf8');
return {
lines: text.split('\n').length,
words: text.split(/\s+/).filter(Boolean).length,
chars: text.length,
};
}filter(Boolean) drops the empty strings that split produces around the blank line, so they aren't counted as words.
2. File extension report
Given a list of file paths, count how many files have each extension (lowercase, without the dot). Files without an extension count as (none).
Expected: { js: 2, md: 1, json: 1, '(none)': 1 }
const path = require('node:path');
const files = ['src/app.js', 'README.md', 'lib/Util.JS', 'package.json', 'Dockerfile'];
const counts = {};
for (const file of files) {
// TODO: use path.extname and count
}
console.log(counts);{}
Show solution
const counts = {};
for (const file of files) {
const ext = path.extname(file).slice(1).toLowerCase() || '(none)';
counts[ext] = (counts[ext] ?? 0) + 1;
}
console.log(counts);3. Event-driven countdown
Create a Countdown class that extends EventEmitter. start(n) should emit tick with the numbers n … 1 and then emit done. Use synchronous emits (no timers) so the output is predictable.
Expected:
tick 3
tick 2
tick 1
Liftoff!const { EventEmitter } = require('node:events');
class Countdown extends EventEmitter {
start(n) {
// TODO: emit 'tick' for n..1, then 'done'
}
}
const c = new Countdown();
c.on('tick', (n) => console.log('tick', n));
c.on('done', () => console.log('Liftoff!'));
c.start(3);
console.log('(end of program)');(end of program)
Show solution
class Countdown extends EventEmitter {
start(n) {
for (let i = n; i >= 1; i--) this.emit('tick', i);
this.emit('done');
}
}4. Fetch all, in order
loadUser(id) simulates a slow database call. Load users 1, 2 and 3 in parallel (not one after another) and print their names in id order.
Expected: [ 'user-1', 'user-2', 'user-3' ]
const { setTimeout: sleep } = require('node:timers/promises');
async function loadUser(id) {
await sleep(40 - id * 10); // later ids answer faster!
return { id, name: `user-${id}` };
}
async function main() {
const ids = [1, 2, 3];
// TODO: load all users in parallel and collect their names
const names = [];
console.log(names);
}
main();[]
Show solution
async function main() {
const ids = [1, 2, 3];
const users = await Promise.all(ids.map(loadUser));
console.log(users.map((u) => u.name));
}Promise.all keeps the results in the order of the input array, no matter which promise finishes first.
5. Query-string parser
Parse the URL below and print the search term, the page as a number (default 1), and the list of all tag values.
Expected:
search: node streams
page: 2
tags: [ 'backend', 'js' ]const link = 'https://shop.example/search?q=node+streams&page=2&tag=backend&tag=js';
// TODO: use new URL(link) and its searchParams
const q = '';
const page = 0;
const tags = [];
console.log('search:', q);
console.log('page:', page);
console.log('tags:', tags);search:
page: 0
tags: []
Show solution
const { searchParams } = new URL(link);
const q = searchParams.get('q');
const page = Number(searchParams.get('page') ?? 1);
const tags = searchParams.getAll('tag');6. File checksum
Write sha256(text) that returns the hex SHA-256 digest of a string, then show that changing a single character changes the whole hash. Print only the first 16 hex characters.
Expected:
hello world -> b94d27b9934d3e08
hello world! -> 7509e5bda0c762d2const crypto = require('node:crypto');
function sha256(text) {
// TODO: use crypto.createHash
return '0000000000000000';
}
for (const s of ['hello world', 'hello world!']) {
console.log(s.padEnd(12), '->', sha256(s).slice(0, 16));
}hello world -> 0000000000000000
hello world! -> 0000000000000000
Show solution
function sha256(text) {
return crypto.createHash('sha256').update(text).digest('hex');
}7. Uppercase transform stream
Create a Transform stream that converts text to upper case, and use pipeline to send the source through it into the collect writable.
Expected: RESULT: STREAMS ARE FUN
const { Readable, Transform, Writable } = require('node:stream');
const { pipeline } = require('node:stream/promises');
const source = Readable.from(['streams ', 'are ', 'fun']);
let result = '';
const collect = new Writable({
write(chunk, encoding, callback) {
result += chunk;
callback();
},
});
const upper = new Transform({
transform(chunk, encoding, callback) {
// TODO: pass the upper-cased chunk on
callback(null, chunk);
},
});
pipeline(source, upper, collect).then(() => console.log('RESULT:', result));RESULT: streams are fun
Show solution
const upper = new Transform({
transform(chunk, encoding, callback) {
callback(null, chunk.toString().toUpperCase());
},
});8. Tiny JSON API
Finish the server so that GET /api/sum?a=2&b=40 answers with JSON { "sum": 42 } and every other URL answers with status 404 and { "error": "Not found" }.
Expected:
200 { sum: 42 }
404 { error: 'Not found' }const http = require('node:http');
const server = http.createServer((req, res) => {
const url = new URL(req.url, 'http://localhost');
res.setHeader('Content-Type', 'application/json');
// TODO: handle /api/sum and the 404 case
res.end(JSON.stringify({ todo: true }));
});
server.listen(0, async () => {
const base = `http://localhost:${server.address().port}`;
for (const path of ['/api/sum?a=2&b=40', '/nope']) {
const res = await fetch(base + path);
console.log(res.status, await res.json());
}
server.close();
});200 { todo: true }
200 { todo: true }
Show solution
const server = http.createServer((req, res) => {
const url = new URL(req.url, 'http://localhost');
res.setHeader('Content-Type', 'application/json');
if (req.method === 'GET' && url.pathname === '/api/sum') {
const a = Number(url.searchParams.get('a'));
const b = Number(url.searchParams.get('b'));
return res.end(JSON.stringify({ sum: a + b }));
}
res.statusCode = 404;
res.end(JSON.stringify({ error: 'Not found' }));
});Test yourself
In exercise 4, why does Promise.all print the users in id order even though user 3 answers first?
- It sorts the results
- Results keep the order of the input array
- It waits for each promise in turn
- By coincidence
Which method returns ALL values of a repeated query parameter like ?tag=a&tag=b?
searchParams.get('tag')searchParams.all('tag')searchParams.getAll('tag')searchParams.tag