Node.js Junior cheat sheet: interview answers

Every question of this level with its correct answer and explanation, on one page for a quick review before the interview.

  1. 1. What is Node.js?

    Correct answer: A JavaScript runtime built on the V8 engine

    Node.js takes the V8 engine from Chrome and adds APIs for the file system, network, processes and more. It is used for servers, CLIs, build tools and scripts.

  2. 2. Which JavaScript engine does Node.js use?

    Correct answer: V8

    V8 is Google's engine, also used in Chrome. SpiderMonkey powers Firefox and JavaScriptCore powers Safari. Other runtimes such as Bun use JavaScriptCore.

  3. 3. What model does Node.js use to handle many connections at once?

    Correct answer: A single-threaded event loop with non-blocking I/O

    JavaScript runs on one main thread. I/O such as reading files or network calls is handed off to the system and libuv, and the callback runs later, so one process can serve thousands of connections.

  4. 4. Which of these is NOT available in Node.js by default?

    Correct answer: document and the DOM

    There is no page in Node.js, so there is no document or window. Instead Node.js provides modules such as fs, http and process. Timers and console exist in both environments.

  5. 5. What is the name of the global object in Node.js?

    Correct answer: global (and globalThis)

    globalThis is the standard name that works in every environment. In Node.js it points to global; in browsers it points to window.

  6. 6. How do you run a file app.js with Node.js?

    Correct answer: node app.js

    The node command executes a file. Running node with no arguments starts the interactive REPL.

  7. 7. What is the Node.js REPL?

    Correct answer: An interactive shell for running JavaScript

    REPL stands for Read-Eval-Print Loop. Start it with node. It supports commands such as .help and .exit, and _ holds the last result.

  8. 8. What does node --watch app.js do?

    Correct answer: Restarts the process when the file or its imports change

    Watch mode is built into Node.js, so tools like nodemon are often no longer needed for simple cases. --watch-path limits which paths are watched.

  9. 9. Which Node.js release lines are recommended for production?

    Correct answer: Active LTS and Maintenance LTS releases

    LTS (Long Term Support) releases get security and bug fixes for about three years. Current releases get new features quickly but have a short support window.

  10. 10. What is libuv in Node.js?

    Correct answer: A C library with the event loop and thread pool

    libuv hides the differences between operating systems (epoll, kqueue, IOCP) and gives Node.js one event loop. It also runs some work, such as file system calls, in a thread pool.

  11. 11. Which two module systems does Node.js support?

    Correct answer: CommonJS (require) and ES modules (import)

    CommonJS is the original Node.js system. ES modules are the language standard and are now fully supported. New projects usually choose ESM.

  12. 12. How do you export a function in CommonJS?

    function add(a, b) {
      return a + b;
    }

    Correct answer: module.exports = { add };

    module.exports is the value that require() returns. export default is ES module syntax. You can also write exports.add = add, but not exports = { add }.

  13. 13. Why does exports = { add } not export anything in CommonJS?

    Correct answer: It reassigns the local variable, not module.exports

    exports starts as a reference to module.exports. Adding properties (exports.add = add) works, but assigning a new object breaks the link. Use module.exports = { add } instead.

  14. 14. How does Node.js decide that a .js file is an ES module?

    Correct answer: "type": "module" in the nearest package.json

    Without "type": "module", .js files are CommonJS. .mjs is always ESM and .cjs is always CommonJS. Recent versions can also detect ESM syntax in ambiguous files.

  15. 15. What is required in an ES module import of a local file that is optional in require()?

    Correct answer: The file extension, as in ./utils.js

    ESM in Node.js follows URL rules, so relative imports must include the extension. require("./utils") can guess .js, .json or index.js.

  16. 16. Which variables are not available in an ES module but exist in CommonJS?

    Correct answer: __dirname and __filename

    CommonJS wraps each file in a function that receives __dirname and __filename. In ESM the same information is on import.meta, including import.meta.url.

  17. 17. What does require() do if the same module is required twice?

    Correct answer: Returns the cached export; the module code runs only once

    Modules are cached after the first load (in require.cache). That's why a module can hold shared state, such as a database connection, for the whole app. ES modules are cached too.

  18. 18. What is the recommended way to import a built-in module?

    Correct answer: With the node: prefix, as in node:fs

    The node: prefix makes it clear the module is built in and cannot be shadowed by a package with the same name in node_modules. Some newer modules, such as node:test, work only with it.

  19. 19. What does import() (with parentheses) do?

    Correct answer: Loads a module at runtime and returns a promise

    Dynamic import() works in both CommonJS and ESM. It is useful for loading code on demand or importing an ES module from CommonJS.

  20. 20. Where does require("lodash") look for the package?

    Correct answer: In node_modules here, then in each parent directory

    Node.js walks up the directory tree looking in each node_modules. Packages installed with -g are not found by require() by default.

  21. 21. What is package.json?

    Correct answer: A file that describes the project and its dependencies

    It is the project manifest. npm init creates it. Fields like type, exports and engines also tell Node.js and npm how to treat the package.

  22. 22. What is the difference between dependencies and devDependencies?

    Correct answer: dependencies run the app; devDependencies help build it

    Test runners, linters and bundlers go in devDependencies (npm i -D). npm install --omit=dev installs only production dependencies, which keeps production images smaller.

  23. 23. What is package-lock.json for?

    Correct answer: It records exact versions, so installs are reproducible

    package.json usually has version ranges like ^4.2.0. The lock file pins the exact tree, including nested dependencies. It should be committed to git.

  24. 24. What does the version range ^1.4.2 allow?

    Correct answer: Any 1.x.x version from 1.4.2 up, but not 2.0.0

    The caret allows minor and patch updates. ~1.4.2 allows only patch updates (1.4.x). For 0.x versions the caret is stricter: ^0.4.2 means >=0.4.2 <0.5.0.

  25. 25. In semantic versioning MAJOR.MINOR.PATCH, when should MAJOR increase?

    Correct answer: When the public API has breaking changes

    MINOR is for new backward-compatible features and PATCH is for backward-compatible bug fixes. Version ranges in package.json rely on this agreement.

  26. 26. How is npm ci different from npm install?

    Correct answer: It installs exactly the lock file and fails on a mismatch

    npm ci is meant for CI and Docker builds where installs must be clean and reproducible. It never changes package.json or the lock file.

  27. 27. How do you run a script defined in package.json like this?

    {
      "scripts": {
        "build": "tsc -p ."
      }
    }

    Correct answer: npm run build

    npm run <name> runs the script with node_modules/.bin on the PATH, so locally installed tools work. start and test also have shortcuts: npm start and npm test.

  28. 28. What does npx do?

    Correct answer: Runs a package's command, local or downloaded

    For example, npx eslint . runs the project's ESLint. It is also handy for one-off tools like project generators, without installing them globally.

  29. 29. Should node_modules be committed to git?

    Correct answer: No: ignore it and commit the lock file instead

    node_modules is large and platform-specific (native modules). Anyone can recreate it exactly from the lock file with npm ci.

  30. 30. What does npm audit do?

    Correct answer: Checks dependencies against known vulnerabilities

    npm audit fix tries to upgrade to safe versions within your ranges. Not every warning is relevant: check whether the vulnerable code is actually reachable in your app.

  31. 31. What does 'non-blocking I/O' mean in Node.js?

    Correct answer: Node.js starts I/O and keeps running other code meanwhile

    While a file is being read or a database is answering, the main thread can serve other requests. Blocking calls like fs.readFileSync stop everything until they finish.

  32. 32. What is an 'error-first callback'?

    fs.readFile("data.txt", "utf8", (err, data) => {
      // ...
    });

    Correct answer: A callback whose first argument is an error or null

    Always check err first. Classic Node.js APIs follow this pattern; most also have promise versions, such as fs/promises.

  33. 33. What is 'callback hell'?

    Correct answer: Deeply nested callbacks that are hard to read and handle

    Promises and async/await flatten the code and let you handle errors in one try/catch.

  34. 34. What is the order of the output?

    console.log("A");
    setTimeout(() => console.log("B"), 0);
    console.log("C");

    Correct answer: A, C, B

    The timer callback goes into the event loop queue and runs only after the current synchronous code finishes, even with a 0 ms delay.

  35. 35. How do you get a promise-based version of the fs API?

    Correct answer: import { readFile } from "node:fs/promises"

    fs/promises has the same functions that return promises, so you can write const text = await readFile(path, "utf8").

  36. 36. What does util.promisify do?

    Correct answer: Turns an error-first callback function into a promise one

    It's useful for old APIs and libraries that only support callbacks. The opposite helper is util.callbackify.

  37. 37. Can you use await at the top level of a file (outside any function) in Node.js?

    Correct answer: Yes, in ES modules

    Top-level await is part of ES modules. In CommonJS you must wrap the code in an async function.

  38. 38. How do you run two independent async requests in parallel and wait for both?

    Correct answer: await Promise.all([getUser(), getOrders()])

    Two awaits in a row run one after another, so the total time is the sum. Promise.all starts both at once and rejects as soon as one fails; Promise.allSettled waits for all results.

  39. 39. What happens if a promise rejects and nothing handles the rejection?

    Correct answer: unhandledRejection fires, and by default the process crashes

    Since Node.js 15, unhandled rejections throw by default. Always await promises inside try/catch or add .catch().

  40. 40. What is an EventEmitter?

    Correct answer: A class for emitting named events and subscribing to them

    Many Node.js objects are EventEmitters: HTTP servers, streams and process. Subscribe with on or once and fire events with emit.

  41. 41. What will this code print?

    import { EventEmitter } from "node:events";
    const bus = new EventEmitter();
    bus.once("ping", () => console.log("pong"));
    bus.emit("ping");
    bus.emit("ping");

    Correct answer: pong once

    once removes the listener after the first call. With on the listener would run every time.

  42. 42. Is emitter.emit() synchronous or asynchronous?

    Correct answer: Synchronous: listeners run immediately, in order

    emit calls listeners one by one before it returns. A slow listener therefore blocks the code that emitted the event.

  43. 43. Why should you avoid fs.readFileSync inside an HTTP request handler?

    Correct answer: It blocks the event loop until the file is read

    Sync calls are fine at startup (loading config) or in CLI scripts. In a server, use fs/promises or streams.

  44. 44. What does path.join("/users", "anna", "../docs", "file.txt") return on Linux?

    Correct answer: /users/docs/file.txt

    path.join joins the segments with the platform separator and normalizes .. and .. It does not check whether the path exists.

  45. 45. How is path.resolve() different from path.join()?

    Correct answer: resolve always returns an absolute path

    path.resolve("a", "b") gives something like /home/me/project/a/b. A segment starting with / resets the result to the root.

  46. 46. Why use the path module instead of joining paths with + "/" +?

    Correct answer: It uses the right separator for each OS and normalizes it

    Windows uses \ while Linux and macOS use /. path also helps with extensions (path.extname) and file names (path.basename).

  47. 47. How do you read an environment variable PORT?

    Correct answer: process.env.PORT

    Values in process.env are always strings (or undefined), so convert them: Number(process.env.PORT ?? 3000).

  48. 48. How can Node.js load variables from a .env file without extra packages?

    Correct answer: node --env-file=.env app.js (or process.loadEnvFile())

    Built-in .env support removed the need for dotenv in many projects. Real secrets in production still come from the environment or a secret manager, not a committed file.

  49. 49. What does process.argv contain?

    Correct answer: node's path, the script's path, then user arguments

    User arguments start at process.argv[2]. For parsing flags you can use the built-in util.parseArgs.

  50. 50. What does process.exit(1) mean?

    Correct answer: Stop the process with an error exit code

    Exit code 0 means success; any other code means failure, which CI and shells check. Prefer setting process.exitCode = 1 and letting the process finish, so pending output is not cut off.

  51. 51. What is the difference between process.cwd() and __dirname?

    Correct answer: cwd() is where Node.js started; __dirname is the file's folder

    If you run node src/app.js from the project root, cwd is the root and __dirname is src. To load files next to the code, build paths from __dirname or import.meta.dirname.

  52. 52. Which module gives information about the operating system, such as CPU count and free memory?

    Correct answer: node:os

    For example, os.availableParallelism() and os.cpus() for CPUs, os.freemem() for memory and os.EOL for the line ending.

  53. 53. How do you append a line to a file using promises?

    Correct answer: await appendFile("log.txt", "line\n") from node:fs/promises

    writeFile replaces the whole file by default. appendFile adds to the end and creates the file if it doesn't exist.

  54. 54. How do you check whether a file exists before reading it?

    Correct answer: Usually you don't: read it and handle ENOENT

    Checking first creates a race condition: the file can be deleted between the check and the read. Handling the error is simpler and correct. fs.exists is deprecated.

  55. 55. What does the error code ENOENT mean?

    Correct answer: No such file or directory

    System errors have a code property. Other common ones: EACCES (permission denied), EADDRINUSE (port in use), ECONNREFUSED (connection refused).

  56. 56. How do you create a folder together with any missing parent folders?

    Correct answer: await mkdir("a/b/c", { recursive: true })

    With recursive: true, mkdir also does not fail if the folder already exists. rm(path, { recursive: true, force: true }) is the matching way to delete a tree.

  57. 57. What does this code do?

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

    Correct answer: Starts a server on port 3000 answering Hello

    The callback runs for every request, whatever the method or URL. Routing by req.method and req.url is up to you, which is why frameworks like Express exist.

  58. 58. What happens if a request handler never calls res.end()?

    Correct answer: The client waits until the request times out

    The response stays open. Every code path, including errors, must finish the response with res.end() or a framework method like res.send().

  59. 59. Can you use fetch() in Node.js without installing a package?

    Correct answer: Yes, fetch is a global in modern Node.js

    Node.js includes fetch, Request, Response, Headers and FormData, built on the undici HTTP client.

  60. 60. What is Express?

    Correct answer: A minimal web framework with routing and middleware

    Express adds routing (app.get("/users", ...)), middleware and response helpers on top of node:http. Fastify, Koa and NestJS are popular alternatives.

  61. 61. What is middleware in Express?

    Correct answer: A (req, res, next) function that runs during request handling

    Middleware runs in the order you register it. Typical uses: parsing the body, logging, authentication, CORS. Forgetting both next() and a response leaves the request hanging.

  62. 62. How do you read the JSON body of a POST request in Express?

    Correct answer: Add app.use(express.json()), then read req.body

    Express doesn't parse bodies by default. express.json() parses application/json; express.urlencoded() handles HTML forms.

  63. 63. How do you read 42 from the URL /users/42 in Express?

    app.get("/users/:id", (req, res) => {
      // ?
    });

    Correct answer: req.params.id

    Route parameters are in req.params and are strings. Query strings like /users?page=2 are in req.query.

  64. 64. Which HTTP status code should an API return when a resource is created?

    Correct answer: 201 Created

    201 is the standard answer to a successful POST that creates something, often with a Location header. 204 means success with no body, common for DELETE.

  65. 65. What is the difference between status codes 401 and 403?

    Correct answer: 401: not authenticated; 403: no permission

    Send 401 when credentials are missing or invalid, and 403 when a logged-in user tries to access something they're not allowed to.

  66. 66. What is CORS, and where is it enforced?

    Correct answer: A browser rule: server headers allow other origins to read responses

    CORS is enforced by browsers. Requests from curl or another server are not affected. In Express it's usually set up with the cors middleware.

  67. 67. How do you catch an error from an awaited promise?

    async function load() {
      const data = await readFile("config.json", "utf8");
      return JSON.parse(data);
    }

    Correct answer: Wrap the code in try { ... } catch (err) { ... }

    Inside an async function, await turns a rejection into a thrown error, so a normal try/catch works. Callers can also use load().catch(...).

  68. 68. What happens when an error is thrown and nothing catches it?

    Correct answer: uncaughtException fires and the process exits

    After an uncaught exception the app may be in a broken state, so the safe approach is to log it and let a process manager (systemd, Docker, Kubernetes, PM2) restart the app.

  69. 69. How do you debug a Node.js app in Chrome DevTools or VS Code?

    Correct answer: Start it with node --inspect app.js and attach

    --inspect opens the inspector protocol; --inspect-brk also pauses on the first line. In Chrome, open chrome://inspect. A debugger; statement sets a breakpoint in code.

  70. 70. What is JSON.parse likely to do with invalid input?

    Correct answer: Throw a SyntaxError

    When parsing data from files, requests or other services, wrap JSON.parse in try/catch, or the error will crash your handler.

  71. 71. What is the built-in way to write tests in Node.js?

    Correct answer: The node:test module, run with node --test

    node:test provides test, describe, it, mocks and coverage, and node:assert provides assertions. Jest and Vitest are still common alternatives.

  72. 72. Can recent Node.js versions run a .ts file directly?

    Correct answer: Yes, they strip the types but don't check them

    Type stripping supports 'erasable' syntax only. Features that need code generation, like enum, need extra flags or a build step. Run tsc --noEmit to check types.

  73. 73. Which statement about console.log in a high-traffic server is true?

    Correct answer: Production apps usually use a structured logger like Pino

    Structured JSON logs with levels (info, warn, error) and fields like request ID are easy to search and filter in log systems.

  74. 74. What does setting NODE_ENV=production usually do?

    Correct answer: Tells libraries to enable production behaviour

    Node.js itself does not treat NODE_ENV specially. It's a convention that frameworks and your own code read to switch behavior.

  75. 75. Why should secrets like database passwords not be hard-coded in the source?

    Correct answer: Code ends up in git and builds; use env vars or a secret manager

    A secret committed once stays in git history. Keep .env files out of git and rotate any secret that was ever committed.