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. 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. 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. 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. Which of these is NOT available in Node.js by default?
Correct answer:
documentand the DOMThere is no page in Node.js, so there is no
documentorwindow. Instead Node.js provides modules such asfs,httpandprocess. Timers andconsoleexist in both environments.5. What is the name of the global object in Node.js?
Correct answer:
global(andglobalThis)globalThisis the standard name that works in every environment. In Node.js it points toglobal; in browsers it points towindow.6. How do you run a file
app.jswith Node.js?Correct answer:
node app.jsThe
nodecommand executes a file. Runningnodewith no arguments starts the interactive REPL.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.helpand.exit, and_holds the last result.8. What does
node --watch app.jsdo?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-pathlimits which paths are watched.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. 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. 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. How do you export a function in CommonJS?
function add(a, b) { return a + b; }Correct answer:
module.exports = { add };module.exportsis the value thatrequire()returns.export defaultis ES module syntax. You can also writeexports.add = add, but notexports = { add }.13. Why does
exports = { add }not export anything in CommonJS?Correct answer: It reassigns the local variable, not
module.exportsexportsstarts as a reference tomodule.exports. Adding properties (exports.add = add) works, but assigning a new object breaks the link. Usemodule.exports = { add }instead.14. How does Node.js decide that a
.jsfile is an ES module?Correct answer:
"type": "module"in the nearestpackage.jsonWithout
"type": "module",.jsfiles are CommonJS..mjsis always ESM and.cjsis always CommonJS. Recent versions can also detect ESM syntax in ambiguous files.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.jsESM in Node.js follows URL rules, so relative imports must include the extension.
require("./utils")can guess.js,.jsonorindex.js.16. Which variables are not available in an ES module but exist in CommonJS?
Correct answer:
__dirnameand__filenameCommonJS wraps each file in a function that receives
__dirnameand__filename. In ESM the same information is onimport.meta, includingimport.meta.url.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. What is the recommended way to import a built-in module?
Correct answer: With the
node:prefix, as innode:fsThe
node:prefix makes it clear the module is built in and cannot be shadowed by a package with the same name innode_modules. Some newer modules, such asnode:test, work only with it.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. Where does
require("lodash")look for the package?Correct answer: In
node_moduleshere, then in each parent directoryNode.js walks up the directory tree looking in each
node_modules. Packages installed with-gare not found byrequire()by default.21. What is
package.json?Correct answer: A file that describes the project and its dependencies
It is the project manifest.
npm initcreates it. Fields liketype,exportsandenginesalso tell Node.js and npm how to treat the package.22. What is the difference between
dependenciesanddevDependencies?Correct answer:
dependenciesrun the app;devDependencieshelp build itTest runners, linters and bundlers go in
devDependencies(npm i -D).npm install --omit=devinstalls only production dependencies, which keeps production images smaller.23. What is
package-lock.jsonfor?Correct answer: It records exact versions, so installs are reproducible
package.jsonusually has version ranges like^4.2.0. The lock file pins the exact tree, including nested dependencies. It should be committed to git.24. What does the version range
^1.4.2allow?Correct answer: Any
1.x.xversion from1.4.2up, but not2.0.0The caret allows minor and patch updates.
~1.4.2allows only patch updates (1.4.x). For0.xversions the caret is stricter:^0.4.2means>=0.4.2 <0.5.0.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.jsonrely on this agreement.26. How is
npm cidifferent fromnpm install?Correct answer: It installs exactly the lock file and fails on a mismatch
npm ciis meant for CI and Docker builds where installs must be clean and reproducible. It never changespackage.jsonor the lock file.27. How do you run a script defined in
package.jsonlike this?{ "scripts": { "build": "tsc -p ." } }Correct answer:
npm run buildnpm run <name>runs the script withnode_modules/.binon the PATH, so locally installed tools work.startandtestalso have shortcuts:npm startandnpm test.28. What does
npxdo?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. Should
node_modulesbe committed to git?Correct answer: No: ignore it and commit the lock file instead
node_modulesis large and platform-specific (native modules). Anyone can recreate it exactly from the lock file withnpm ci.30. What does
npm auditdo?Correct answer: Checks dependencies against known vulnerabilities
npm audit fixtries 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. 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.readFileSyncstop everything until they finish.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
nullAlways check
errfirst. Classic Node.js APIs follow this pattern; most also have promise versions, such asfs/promises.33. What is 'callback hell'?
Correct answer: Deeply nested callbacks that are hard to read and handle
Promises and
async/awaitflatten the code and let you handle errors in onetry/catch.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. How do you get a promise-based version of the
fsAPI?Correct answer:
import { readFile } from "node:fs/promises"fs/promiseshas the same functions that return promises, so you can writeconst text = await readFile(path, "utf8").36. What does
util.promisifydo?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. Can you use
awaitat the top level of a file (outside any function) in Node.js?Correct answer: Yes, in ES modules
Top-level
awaitis part of ES modules. In CommonJS you must wrap the code in anasyncfunction.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.allstarts both at once and rejects as soon as one fails;Promise.allSettledwaits for all results.39. What happens if a promise rejects and nothing handles the rejection?
Correct answer:
unhandledRejectionfires, and by default the process crashesSince Node.js 15, unhandled rejections throw by default. Always
awaitpromises insidetry/catchor add.catch().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 withonoronceand fire events withemit.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:
pongonceonceremoves the listener after the first call. Withonthe listener would run every time.42. Is
emitter.emit()synchronous or asynchronous?Correct answer: Synchronous: listeners run immediately, in order
emitcalls listeners one by one before it returns. A slow listener therefore blocks the code that emitted the event.43. Why should you avoid
fs.readFileSyncinside 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/promisesor streams.44. What does
path.join("/users", "anna", "../docs", "file.txt")return on Linux?Correct answer:
/users/docs/file.txtpath.joinjoins the segments with the platform separator and normalizes..and.. It does not check whether the path exists.45. How is
path.resolve()different frompath.join()?Correct answer:
resolvealways returns an absolute pathpath.resolve("a", "b")gives something like/home/me/project/a/b. A segment starting with/resets the result to the root.46. Why use the
pathmodule 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/.pathalso helps with extensions (path.extname) and file names (path.basename).47. How do you read an environment variable
PORT?Correct answer:
process.env.PORTValues in
process.envare always strings (orundefined), so convert them:Number(process.env.PORT ?? 3000).48. How can Node.js load variables from a
.envfile without extra packages?Correct answer:
node --env-file=.env app.js(orprocess.loadEnvFile())Built-in
.envsupport removed the need fordotenvin many projects. Real secrets in production still come from the environment or a secret manager, not a committed file.49. What does
process.argvcontain?Correct answer:
node's path, the script's path, then user argumentsUser arguments start at
process.argv[2]. For parsing flags you can use the built-inutil.parseArgs.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 = 1and letting the process finish, so pending output is not cut off.51. What is the difference between
process.cwd()and__dirname?Correct answer:
cwd()is where Node.js started;__dirnameis the file's folderIf you run
node src/app.jsfrom the project root,cwdis the root and__dirnameissrc. To load files next to the code, build paths from__dirnameorimport.meta.dirname.52. Which module gives information about the operating system, such as CPU count and free memory?
Correct answer:
node:osFor example,
os.availableParallelism()andos.cpus()for CPUs,os.freemem()for memory andos.EOLfor the line ending.53. How do you append a line to a file using promises?
Correct answer:
await appendFile("log.txt", "line\n")fromnode:fs/promiseswriteFilereplaces the whole file by default.appendFileadds to the end and creates the file if it doesn't exist.54. How do you check whether a file exists before reading it?
Correct answer: Usually you don't: read it and handle
ENOENTChecking first creates a race condition: the file can be deleted between the check and the read. Handling the error is simpler and correct.
fs.existsis deprecated.55. What does the error code
ENOENTmean?Correct answer: No such file or directory
System errors have a
codeproperty. Other common ones:EACCES(permission denied),EADDRINUSE(port in use),ECONNREFUSED(connection refused).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,mkdiralso does not fail if the folder already exists.rm(path, { recursive: true, force: true })is the matching way to delete a tree.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
HelloThe callback runs for every request, whatever the method or URL. Routing by
req.methodandreq.urlis up to you, which is why frameworks like Express exist.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 likeres.send().59. Can you use
fetch()in Node.js without installing a package?Correct answer: Yes,
fetchis a global in modern Node.jsNode.js includes
fetch,Request,Response,HeadersandFormData, built on the undici HTTP client.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 ofnode:http. Fastify, Koa and NestJS are popular alternatives.61. What is middleware in Express?
Correct answer: A
(req, res, next)function that runs during request handlingMiddleware 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. How do you read the JSON body of a POST request in Express?
Correct answer: Add
app.use(express.json()), then readreq.bodyExpress doesn't parse bodies by default.
express.json()parsesapplication/json;express.urlencoded()handles HTML forms.63. How do you read
42from the URL/users/42in Express?app.get("/users/:id", (req, res) => { // ? });Correct answer:
req.params.idRoute parameters are in
req.paramsand are strings. Query strings like/users?page=2are inreq.query.64. Which HTTP status code should an API return when a resource is created?
Correct answer:
201 Created201 is the standard answer to a successful POST that creates something, often with a
Locationheader. 204 means success with no body, common for DELETE.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. 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
corsmiddleware.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
asyncfunction,awaitturns a rejection into a thrown error, so a normaltry/catchworks. Callers can also useload().catch(...).68. What happens when an error is thrown and nothing catches it?
Correct answer:
uncaughtExceptionfires and the process exitsAfter 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. How do you debug a Node.js app in Chrome DevTools or VS Code?
Correct answer: Start it with
node --inspect app.jsand attach--inspectopens the inspector protocol;--inspect-brkalso pauses on the first line. In Chrome, openchrome://inspect. Adebugger;statement sets a breakpoint in code.70. What is
JSON.parselikely to do with invalid input?Correct answer: Throw a
SyntaxErrorWhen parsing data from files, requests or other services, wrap
JSON.parseintry/catch, or the error will crash your handler.71. What is the built-in way to write tests in Node.js?
Correct answer: The
node:testmodule, run withnode --testnode:testprovidestest,describe,it, mocks and coverage, andnode:assertprovides assertions. Jest and Vitest are still common alternatives.72. Can recent Node.js versions run a
.tsfile 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. Runtsc --noEmitto check types.73. Which statement about
console.login 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. What does setting
NODE_ENV=productionusually do?Correct answer: Tells libraries to enable production behaviour
Node.js itself does not treat
NODE_ENVspecially. It's a convention that frameworks and your own code read to switch behavior.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
.envfiles out of git and rotate any secret that was ever committed.