Skip to content

Coding practice

Node.js Coding Questions

20 hands-on challenges with prompts and solution sketches for Node.js interview rounds.

Challenge set

20 coding questions

1. Read File Async

javascript

Read a UTF-8 file with fs/promises.

import { readFile } from "node:fs/promises";
const text = await readFile("./notes.txt", "utf8");

2. Create HTTP Server

javascript

Start a basic HTTP server.

import http from "node:http";
const server = http.createServer((req, res) => {
  res.writeHead(200, { "Content-Type": "text/plain" });
  res.end("ok");
});
server.listen(3000);

3. Stream Pipeline

javascript

Pipe a file to response with pipeline.

import { createReadStream } from "node:fs";
import { pipeline } from "node:stream/promises";
await pipeline(createReadStream("./file.txt"), res);

4. Path Join

javascript

Build a safe absolute path.

import path from "node:path";
const filePath = path.join(process.cwd(), "data", "users.json");

5. Env Config

javascript

Read and validate an env var.

const port = Number(process.env.PORT ?? 3000);
if (!Number.isFinite(port)) throw new Error("Invalid PORT");

6. Event Emitter Bus

javascript

Use EventEmitter for app events.

import { EventEmitter } from "node:events";
export const bus = new EventEmitter();
bus.on("user:created", (user) => console.log(user.id));

7. Child Process Exec

javascript

Run a shell command with execFile.

import { execFile } from "node:child_process";
import { promisify } from "node:util";
const execFileAsync = promisify(execFile);
const { stdout } = await execFileAsync("node", ["-v"]);

8. Buffer to String

javascript

Convert a buffer to UTF-8 string.

const buf = Buffer.from("hello");
const text = buf.toString("utf8");

9. JSON File Write

javascript

Write JSON atomically-ish with writeFile.

import { writeFile } from "node:fs/promises";
await writeFile("./out.json", JSON.stringify(data, null, 2), "utf8");

10. URL Parse

javascript

Parse request URL pathname and query.

const url = new URL(req.url, "http://localhost");
const page = url.searchParams.get("page");

11. Middleware Style

javascript

Compose simple middleware functions.

function compose(middlewares) {
  return async (ctx) => {
    let i = -1;
    const dispatch = async (index) => {
      if (index <= i) throw new Error("next() called multiple times");
      i = index;
      const fn = middlewares[index];
      if (fn) await fn(ctx, () => dispatch(index + 1));
    };
    await dispatch(0);
  };
}

12. Graceful Shutdown

javascript

Close server on SIGTERM.

process.on("SIGTERM", () => {
  server.close(() => process.exit(0));
});

13. Crypto Hash

javascript

Hash a password with sha256 (demo only).

import { createHash } from "node:crypto";
const hash = createHash("sha256").update(password).digest("hex");

14. Worker Threads

javascript

Offload CPU work to a worker.

import { Worker } from "node:worker_threads";
const worker = new Worker("./worker.js", { workerData: { n: 40 } });
worker.on("message", console.log);

15. Fetch in Node

javascript

Call an API with native fetch.

const res = await fetch("https://api.example.com/health");
if (!res.ok) throw new Error("Request failed");
const data = await res.json();

16. Cluster Stub

javascript

Fork workers based on CPU count.

import cluster from "node:cluster";
import os from "node:os";
if (cluster.isPrimary) {
  for (let i = 0; i < os.availableParallelism(); i++) cluster.fork();
} else {
  // start server
}

17. Temp Directory

javascript

Create and use a temp directory.

import { mkdtemp } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
const dir = await mkdtemp(path.join(tmpdir(), "app-"));

18. AbortController Timeout

javascript

Abort fetch after timeout.

const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 3000);
try {
  await fetch(url, { signal: controller.signal });
} finally {
  clearTimeout(timer);
}

19. Module Path URL

javascript

Resolve __dirname in ESM.

import path from "node:path";
import { fileURLToPath } from "node:url";
const __dirname = path.dirname(fileURLToPath(import.meta.url));

20. Rate Limit Map

javascript

Simple in-memory rate limiter.

const hits = new Map();
function allow(ip) {
  const now = Date.now();
  const entry = hits.get(ip) ?? [];
  const recent = entry.filter((t) => now - t < 60_000);
  if (recent.length >= 60) return false;
  recent.push(now);
  hits.set(ip, recent);
  return true;
}