Node.js and Express: event loop, modules and building APIs – Server Side interview prep

261 interview-style multiple-choice questions on Node.js and Express: event loop, modules and building APIs, organized by topic: concepts, scenarios, code to read and tradeoffs, each with a short explanation. Learn the 162 key terms with the flashcards first, then test yourself.

Take the practice test · Flashcards · All study tools

What it covers

  1. 9.1 The runtime, threads and the event loop
  2. 9.2 Modules, configuration and the process
  3. 9.3 Streams, buffers and events
  4. 9.4 Core APIs: files, HTTP, crypto and child processes
  5. 9.5 Express
  6. 9.6 Fastify, NestJS and other frameworks
  7. 9.7 Security for Node.js apps
  8. 9.8 Testing, debugging and tooling
  9. 9.9 Production and operations

Key terms

9.1 The runtime, threads and the event loop

V8
Google's JavaScript engine used by Node.js
libuv
Library providing Node's event loop and async I/O
Event loop
Loop that runs callbacks when operations complete
Worker threads
Node.js threads for CPU-heavy JavaScript
UV_THREADPOOL_SIZE
libuv pool size
Thread pool contention
Crypto and fs share pool
monitorEventLoopDelay
Loop delay histogram
Error-first callback
(err, result)
globalThis
The global object
import.meta.dirname
ESM __dirname
process.argv
Command-line args
heapUsed vs rss
JS heap vs whole process
unref()
Don't keep process alive
worker vs fork
Thread vs process
Piscina
Worker pool
node: prefix
Built-in module
Node-API
Stable native addon API
dns.lookup
OS resolver on pool
availableParallelism
Pool sizing

9.2 Modules, configuration and the process

module.exports
CommonJS export object
require cache
Modules run once
createRequire
require inside ESM
Env vars are strings
Convert types
--env-file
Built-in .env loading
bin field
Install a CLI
node_modules lookup
Walks up folders
--import
Preload ESM
Subpath imports
#-prefixed aliases
Syntax detection
Typeless ESM files
require.main
Run directly check
Module wrapper
Provides require, module
util.parseArgs
Built-in flag parser
cwd vs __dirname
Start dir vs file dir
NODE_OPTIONS
Flags via env

9.3 Streams, buffers and events

CommonJS
Node's original module system with require
ES modules
Standard import/export modules
Stream
Interface for processing data in chunks
Backpressure
Flow control when a consumer is slower than a producer
Stream types
Readable, Writable, Duplex, Transform
Transform
Modify data in flight
objectMode
Stream JS values
highWaterMark
Buffer threshold
Flowing mode
data events push
EventTarget
addEventListener in Node
events.on
Async iterator of events
Buffer
Raw binary data
byteLength
Bytes, not characters
allocUnsafe
Uninitialized memory
setEncoding
Safe text decoding
Readable.toWeb
Node to web stream
destroy()
Abort a stream
end vs finish
Readable vs writable done
cork/uncork
Batch writes

9.4 Core APIs: files, HTTP, crypto and child processes

fs/promises
Promise-based file API
path.join
Safe path building
Error codes
ENOENT, EACCES, EADDRINUSE
fs.watch
Platform-dependent watcher
rm recursive force
Delete a tree
res.end()
Finish the response
headersTimeout
Slow client limit
Keep-alive agent
Reuse outgoing connections
Ed25519 key pair
Sign and verify
crypto.scrypt
Built-in password KDF
execFile
No shell, no injection
stdio inherit
Share parent's streams
URL searchParams
Parse query strings
node:sqlite
Built-in SQLite
EMFILE
Too many open files
crypto.subtle
Web Crypto in Node
GCM nonce
Never reuse an IV
listen(0)
Random free port

9.5 Express

Middleware
Function in the request pipeline that can call next()
Error middleware
Express handler with (err, req, res, next)
express.json()
Body parser for JSON requests
Router
Modular group of routes
Express 5 wildcards
Named, like /*splat
Middleware order
Registration order
next()
Pass control on
next(err)
Jump to error handlers
res.json
Serialize and send
req.params/query/body
Path, query, body
express.static
Serve files
express.urlencoded
Form body parser
404 handler
Final middleware
Headers already sent
Double response
trust proxy
Real client IP
Shared rate limit store
Count across instances
MemoryStore
Dev-only session store
multer
Multipart uploads
res.locals
Per-request data
res.render
Server-side templates

9.6 Fastify, NestJS and other frameworks

Fastify response schema
Fast, filtered serialization
Encapsulation
Plugin scope isolation
Hooks
Lifecycle functions
decorate
Extend instance
inject()
Test without network
Type provider
Schema-driven types
NestJS
Modules, controllers, providers
ValidationPipe
DTO validation
Guard
canActivate check
Interceptor
Around handler logic
Exception filter
Errors to responses
Hono
Web-standard framework
Koa
Onion middleware
Prisma/Drizzle
TS ORMs
BullMQ
Redis job queue

9.7 Security for Node.js apps

Path traversal fix
Resolve, then check prefix
--disable-proto
Remove __proto__
re2
Linear-time regex
vm module
Not a sandbox
audit fix --force
Breaking upgrades
--permission
Node permission model
Pino redact
Mask secrets in logs
NoSQL injection
Operator objects in input
Simple query parser
Express 5 default
pnpm script policy
Install scripts off
npm sbom
Bill of materials
Lockfile integrity
Package hash check
res.send string
text/html body
Parameter pollution
Repeated query keys
npm ci --omit=dev
No dev deps in prod
NODE_TLS_REJECT_UNAUTHORIZED
Disables cert checks
resourceLimits
Cap worker memory

9.8 Testing, debugging and tooling

t.mock.method
Mock a method
node --test
Built-in test runner
supertest
HTTP tests for apps
MockAgent
Mock fetch in Node
deepStrictEqual
Recursive equality
--inspect
DevTools debugging
--inspect-brk
Break on first line
--cpu-prof
CPU profile file
--heapsnapshot-signal
Snapshot on signal
Clinic.js
Performance diagnosis
--watch
Restart on change
tsx
Run TS in dev
node --run
Run package scripts
Async stack traces
at async frames
NODE_DEBUG
Core module debug logs
autocannon
HTTP load testing
Diagnostic report
Process state JSON
--enable-source-maps
TS stack traces

9.9 Production and operations

cluster module
Runs several Node.js processes sharing a port
SIGTERM
Signal asking a process to shut down
Heap snapshot
Memory dump used to find leaks
npm audit
Vulnerability check for dependencies
pm2 reload
Rolling worker restart
One process per container
Let the orchestrator scale
Heap headroom
Below container limit
OTel preload
Instrument before load
Forced exit timer
Shutdown deadline
closeIdleConnections
Drop idle keep-alives
Per-instance cache
Not shared
under-pressure
Event-loop-based shedding
Reverse proxy
TLS, static, buffering
Pino
Fast JSON logging
prom-client
Prometheus metrics
SEA
Single executable app
node as PID
Direct signals
ELU
Event loop utilization
Compile cache
Faster startup
ECONNRESET
Client hung up
LTS phases
Active, Maintenance, EOL

Sample practice questions

  1. What is Node.js?

    1. A document database written entirely in JavaScript
    2. A browser extension that runs scripts on web pages
    3. A V8-based runtime for JavaScript outside the browser
    4. A JavaScript framework for building user interfaces

    Answer: C. A V8-based runtime for JavaScript outside the browser libuv provides the event loop and asynchronous I/O underneath.

  2. What is the difference between CommonJS and ES modules in Node.js?

    1. They're the same module system, just with different file extensions
    2. CommonJS is the newer standard, and ES modules are the legacy system
    3. ES modules can't be used in Node.js at all, only in browsers
    4. CommonJS uses `require`; ESM uses `import`, via `.mjs` or `"type": "module"`

    Answer: D. CommonJS uses `require`; ESM uses `import`, via `.mjs` or `"type": "module"` ES modules load asynchronously and support top-level `await`.

  3. Why are streams useful for handling large files in Node.js?

    1. They make the files take up less space on disk
    2. They make the file read faster than reading at once
    3. They encrypt the data automatically as it flows
    4. They process data in chunks, keeping memory use low

    Answer: D. They process data in chunks, keeping memory use low `fs.createReadStream` plus `pipeline` is the usual pattern.

  4. What does `fs.readFileSync` do inside an HTTP request handler?

    1. It reads in a background thread without blocking anything
    2. It throws an error whenever it's used inside a server
    3. It caches the file's contents in memory forever
    4. It blocks the event loop, delaying every other request

    Answer: D. It blocks the event loop, delaying every other request Use `fs.promises.readFile` or streams in request handlers.

  5. What is middleware in Express?

    1. A routing table stored in a JSON configuration file
    2. A plugin that extends the V8 engine with new features
    3. A database access layer that ships built into Express
    4. A `(req, res, next)` function that handles the request or calls `next()`

    Answer: D. A `(req, res, next)` function that handles the request or calls `next()` Middleware runs in the order it's registered.

  6. Which is a modern alternative framework to Express with schema-based validation and a focus on performance?

    1. Mocha
    2. Fastify
    3. jQuery
    4. Lodash

    Answer: B. Fastify NestJS is another popular option, adding structure and dependency injection.

  7. What does `helmet` add to an Express app?

    1. A pooled database connection manager
    2. Security headers like CSP and HSTS
    3. Automatic HTTPS certificates from Let's Encrypt
    4. User authentication and login routes

    Answer: B. Security headers like CSP and HSTS It's a quick baseline, not a complete security solution.

  8. Which tool helps diagnose a memory leak in a Node.js process?

    1. ESLint, with its memory-leak rule set
    2. `console.log` of every variable in the app
    3. Heap snapshots compared over time in DevTools
    4. `npm audit`, which reports leaky packages

    Answer: C. Heap snapshots compared over time in DevTools Look for object counts that keep growing between snapshots.

  9. How can a Node.js app use all the CPU cores on one machine?

    1. Rewrite more of the code to use `async` functions
    2. Run several processes, via `cluster`, PM2 or containers
    3. Raise the libuv thread pool size to match the core count
    4. Do nothing; Node.js spreads JavaScript across all cores

    Answer: B. Run several processes, via `cluster`, PM2 or containers Each process has its own memory, so shared state must live elsewhere.

  10. Why can one Node.js process handle many concurrent connections?

    1. It forks a separate child process for every incoming request
    2. It queues requests and handles each one fully, one at a time
    3. It quietly starts a new OS thread for every incoming request
    4. Non-blocking I/O and an event loop let one thread juggle many waits

    Answer: D. Non-blocking I/O and an event loop let one thread juggle many waits The catch: CPU-heavy JavaScript blocks everything else on that thread.

Practice all 261 questions

More Server Side