NodeJS Interview Cheat Sheet
Top 50 interview questions with concise answers. Print this page or save as PDF for offline study.
1. What is Node.js?
Node.js is a JavaScript runtime built on Chrome's V8 engine that lets you run JavaScript on the server side — outside the browser. It's built around a non-blocking, event-driven architecture, which makes it great for building fast, scalable network applications like APIs, real-time apps, and microservices.
2. Why was Node.js created?
Node.js was created by Ryan Dahl in 2009 to solve the problem of handling many simultaneous connections efficiently. Traditional servers (Apache) blocked on I/O — each request tied up a thread. Node uses an event-driven, non-blocking model so one thread handles thousands of concurrent I/O operations without waiting.
3. What is the V8 engine in Node.js?
V8 is Google's open-source JavaScript engine — the same one that runs JavaScript in Chrome. It compiles JavaScript directly to native machine code (JIT compilation) instead of interpreting it, making it very fast. Node.js uses V8 under the hood to execute your server-side JavaScript code.
4. What is the event loop in Node.js?
The event loop is the core of Node.js — it's what allows JavaScript to handle multiple operations without blocking. It continuously checks if there are pending callbacks to run (timers, I/O, network). When an async operation completes, the event loop picks up the callback and runs it. This is how Node handles many connections with one thread.
5. What is single-threaded architecture?
Single-threaded means Node.js runs JavaScript on one main thread — unlike traditional servers that create a new thread per request. Instead of threading, Node uses asynchronous callbacks to handle concurrency. The single thread is never blocked because I/O operations run in the background (via libuv) and notify the main thread when done.
6. What is npm?
npm (Node Package Manager) is the default package manager for Node.js. It lets you install, share, and manage JavaScript libraries (packages) that you use in your project. npm install adds a package; package.json tracks which packages your project depends on. The npm registry hosts over 2 million packages.
7. What is a package.json file?
package.json is the configuration file for your Node.js project. It tracks your project name, version, scripts (npm start, npm test), and dependencies — the packages your app needs. Anyone who clones your repo can run npm install and get all the same packages installed automatically.
8. What are dependencies and devDependencies?
dependencies are packages needed in production — express, mongoose, jsonwebtoken. devDependencies are only needed during development — jest, nodemon, eslint. When you deploy to production, you can run npm install --production to skip devDependencies and keep the deployment lean. Separating them keeps production clean.
9. What is a callback function?
A callback is a function you pass to another function to be called when an operation finishes. In Node.js: fs.readFile('file.txt', callback) — Node reads the file async and calls your callback when done. Callbacks are the original way to handle async operations before Promises and async/await made it cleaner.
10. What is a module in Node.js?
A module is a reusable piece of code in its own file. Node uses the module system to keep code organized and prevent variable name collisions. You export what you want to share (module.exports) and import what you need (require()). Every file in Node.js is automatically its own module.
11. What is CommonJS?
CommonJS (CJS) is the original module system in Node.js — it uses require() to import and module.exports to export. It loads modules synchronously, which is fine for server-side code. It's still the default in most Node.js projects, though ES Modules (import/export) are now also supported.
12. What is the fs module used for?
The fs module provides functions for working with the file system — reading files, writing files, creating directories, checking if a file exists. Node has both sync versions (fs.readFileSync — blocks until done) and async versions (fs.readFile — non-blocking with a callback). Always prefer async in production to avoid blocking the event loop.
13. What is the path module used for?
The path module helps you work with file and directory paths in a cross-platform way. It handles differences between operating systems (Windows uses backslashes, Unix uses forward slashes). path.join(__dirname, 'public', 'index.html') correctly builds a path regardless of the OS.
14. What is the os module?
The os module provides information about the operating system — CPU count, total memory, free memory, hostname, platform (win32, linux, darwin). Useful for building health checks, monitoring dashboards, or scaling logic that adapts based on available system resources.
15. What is a buffer in Node.js?
A Buffer is a fixed-size chunk of raw binary data — like a byte array. Node.js uses Buffers when dealing with binary data: reading files, receiving network packets, processing images. Buffers exist outside the V8 heap and are necessary because JavaScript strings are UTF-16 encoded and can't efficiently represent raw binary.
16. What is a stream in Node.js?
A stream is a sequence of data delivered in chunks over time instead of all at once. Node.js uses streams for reading large files, piping HTTP responses, and processing data without loading everything into memory. Types: Readable (data comes in), Writable (data goes out), Duplex (both), Transform (modifies data in transit).
17. What is server-side JavaScript?
Server-side JavaScript means running JavaScript code on the server (Node.js) instead of the browser. You use the same language for both frontend and backend, share code between them, and build full-stack apps with one language. The server handles requests, talks to databases, and sends back responses — all in JavaScript.
18. What is the http module used for?
The http module is Node's built-in way to create HTTP servers and make HTTP requests. http.createServer() creates a server that listens on a port and receives requests. It's the foundation that frameworks like Express are built on. You rarely use it directly — Express provides a cleaner API on top of it.
19. What is middleware?
Middleware is a function that sits between the request and response in the request pipeline. It receives the request, can modify it, perform logic (authentication, logging, parsing), and either send a response or pass control to the next middleware. In Express: app.use((req, res, next) => { ... next(); }).
20. What is Express.js?
Express.js is a minimal web framework for Node.js that makes it easy to build APIs and web apps. It provides routing (match URLs to handler functions), middleware support (plug in authentication, logging, parsing), template rendering, and error handling — with far less boilerplate than raw Node.js http module.
21. What is routing in Node and Express?
Routing maps incoming HTTP requests (URL + method) to handler functions. In Express: app.get('/users', handler) handles GET requests to /users; app.post('/users', handler) handles POST. Routes let you organize your API into clean, meaningful endpoints. Express Router lets you group related routes into separate files.
22. What is JSON in Node.js?
JSON (JavaScript Object Notation) is the standard data format for APIs. Node.js has JSON.parse() to convert a JSON string to a JavaScript object, and JSON.stringify() to convert an object to a JSON string. Express's res.json() automatically serializes your response object and sets the Content-Type header to application/json.
23. What is an API endpoint?
An API endpoint is a specific URL that your server exposes for clients to interact with. GET /api/users returns the user list; POST /api/users creates a new user; DELETE /api/users/123 deletes user 123. Each endpoint maps to a handler function in your server code that performs the appropriate operation.
24. What is an environment variable?
Environment variables are key-value pairs set outside your code that configure your application — database URL, API keys, port numbers, environment name. They let the same code run differently in dev vs prod without changing the code. You access them in Node.js via process.env.MY_VARIABLE.
25. What is process.env?
process.env is an object in Node.js that contains all environment variables set in the system or .env file. process.env.PORT gives you the port to listen on; process.env.DB_URL gives the database connection string. Never hardcode secrets in code — read them from process.env instead.
26. What is nodemon?
nodemon is a development tool that automatically restarts your Node.js server when you change a file. Instead of manually stopping and restarting after every code change, nodemon watches your files and does it for you. Install as devDependency and run: nodemon server.js. It's a standard part of the Node.js dev workflow.
27. What is asynchronous programming in Node?
Asynchronous programming means starting an operation (file read, database query, API call) and continuing to do other work while waiting for it to finish. When the operation completes, the callback, Promise, or async/await resumes. This is how Node.js serves many requests simultaneously with one thread — nobody waits for nobody.
28. What is synchronous programming?
Synchronous programming runs operations one at a time — each line waits for the previous to finish. Simple to reason about but inefficient for I/O: fs.readFileSync blocks the entire Node.js thread while reading, preventing it from handling other requests. Fine for scripts; avoid in web servers handling concurrent requests.
29. What is an error-first callback?
An error-first callback is Node.js's convention: the first parameter of the callback is always an error (null if no error, Error object if something went wrong). The second parameter is the result. Always check the error first: if (err) return handleError(err). This pattern predates Promises but is still common in many Node APIs.
30. Difference between console.log and return?
console.log outputs something to stdout — it's a side effect for visibility/debugging. return ends the function and passes a value back to the caller. They serve completely different purposes: console.log is for printing; return is for passing data. A function can console.log and return at the same time.
31. What is the difference between synchronous and asynchronous file operations in Node.js?
Sync file ops (readFileSync, writeFileSync) block the event loop — the entire Node.js process freezes until the file operation completes. No other requests can be handled during that time. Async file ops (readFile, writeFile) hand the work off to libuv, return immediately, and call your callback when done. In a web server, always use async.
32. What is the role of the event emitter?
EventEmitter is Node.js's built-in pub-sub mechanism. Objects that extend EventEmitter can emit named events (emitter.emit('data', value)) and listeners can subscribe (emitter.on('data', handler)). Many Node.js core modules (streams, http server, child processes) are EventEmitters. It's the foundation of event-driven architecture in Node.
33. How does Node.js handle concurrency if it is single-threaded?
Node.js is single-threaded for JavaScript, but libuv (its async I/O library) uses a thread pool for blocking operations like file system and DNS. The event loop delegates I/O to libuv, stays free to handle other events, and picks up the callback when libuv finishes. So concurrency is achieved through async I/O, not multiple threads.
34. What is middleware chaining in Express.js?
Middleware chaining in Express means each middleware calls next() to pass control to the next one in line. The chain runs in the order you define them: logging → authentication → body parsing → route handler. If any middleware doesn't call next() or send a response, the request just hangs. Order matters significantly.
35. What is CORS and why is it needed?
CORS (Cross-Origin Resource Sharing) is a browser security mechanism that blocks frontend code from making requests to a different domain. Your React app on localhost:3000 can't call your API on localhost:5000 without CORS headers. The server must send Access-Control-Allow-Origin headers to grant permission. The cors npm package makes this easy in Express.
36. What is the difference between PUT and PATCH?
PUT replaces the entire resource — you send the complete updated object and the server overwrites everything. PATCH partially updates — you send only the fields that changed. PUT is idempotent and clearer for full replacements; PATCH is more efficient when changing a single field in a large object.
37. What is the purpose of Express.js router?
Express Router lets you split routes into separate files and group related ones together. You create a router (const router = express.Router()), define routes on it, and mount it on a path (app.use('/api/users', userRouter)). Keeps your codebase organized — user routes in users.js, order routes in orders.js, etc.
38. How does Node.js handle errors in asynchronous code?
In async code, errors propagate through Promise rejections and callback err parameters. In Express, passing an error to next(err) triggers error-handling middleware. Unhandled Promise rejections in older Node versions crashed the process silently — Node 15+ throws them as errors. Always use try/catch in async handlers and pass errors to next().
39. What is a promise in Node.js?
A Promise is an object representing the eventual completion (or failure) of an async operation. Instead of nested callbacks (callback hell), you chain .then() and .catch(). A Promise is in one of three states: pending, fulfilled (resolved with a value), or rejected (rejected with an error). Cleaner than callbacks for async code.
40. What is async/await and why is it useful?
async/await is syntactic sugar over Promises that makes async code look like synchronous code. Mark a function async and use await inside it to pause execution until a Promise resolves. Errors throw naturally and are caught with try/catch. It dramatically improves readability compared to chained .then() calls.
41. What is the purpose of the cluster module in Node.js?
The cluster module lets you create multiple Node.js worker processes that all share the same server port. Since Node.js is single-threaded, cluster spawns one worker per CPU core — each worker handles its own event loop. The master process distributes incoming connections across workers. This is how Node.js uses all CPU cores.
42. What is rate limiting in Node.js?
Rate limiting restricts how many requests a client can make in a given time window. Without it, a single client can spam your API with thousands of requests per second — slowing or crashing it. Use express-rate-limit to add: 100 requests per 15 minutes per IP. Essential for preventing abuse, DDoS, and brute-force attacks.
43. What are HTTP status codes and why are they important?
HTTP status codes tell the client what happened: 200 (OK), 201 (Created), 400 (Bad Request — client error), 401 (Unauthorized), 403 (Forbidden), 404 (Not Found), 500 (Internal Server Error). Returning the right status code helps clients handle responses correctly and makes APIs self-documenting and debuggable.
44. What is streaming in Node.js?
Streaming sends data in chunks as it's produced instead of buffering the entire response. For large files or real-time data, streaming means the client starts receiving data immediately — no waiting. Node.js streams pipe data from source to destination: readableStream.pipe(response) sends a file to the client without loading it all into memory.
45. What is a template engine in Node.js?
A template engine (EJS, Handlebars, Pug) renders HTML on the server by combining a template with data. Instead of sending JSON to a React frontend, you render HTML directly on the server and send it. Useful for traditional multi-page apps or email generation. Less common now that SPAs and APIs dominate.
46. What is JSON Web Token (JWT)?
JWT is a compact, self-contained token for authentication. It contains three parts (header.payload.signature) — the payload carries user data (id, role), and the signature verifies it wasn't tampered with. Server issues a JWT on login; the client sends it in the Authorization header on subsequent requests. No session storage needed.
47. What is the difference between global and local npm installation?
Global installation (npm install -g) installs the package for use as a CLI command anywhere on your machine — like installing nodemon globally. Local installation (npm install) installs into node_modules in the current project. For libraries you import in code, always install locally — global packages aren't part of your project's dependency tree.
48. What is nodemailer and where is it used?
nodemailer is a Node.js library for sending emails from your app — sign-up confirmations, password resets, notifications. Configure it with your email provider (SMTP, Gmail, SendGrid) and call transporter.sendMail() with the recipient, subject, and body. It's the go-to email solution for Node.js backends.
49. What is dotenv and why is it used?
dotenv loads environment variables from a .env file into process.env. Instead of setting environment variables in your OS or CI pipeline for local development, you create a .env file with DATABASE_URL=xxx, add it to .gitignore (never commit it), and dotenv makes them available as process.env.DATABASE_URL when the app starts.
50. What is body parsing in Express.js?
HTTP requests from clients arrive with bodies (JSON, form data, raw text). By default, Express doesn't parse them — you must add middleware. express.json() parses JSON bodies; express.urlencoded() parses form data. Without body parsing, req.body is undefined. These are included in Express 4.16+ — no need for the separate body-parser package.