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
- 9.1 The runtime, threads and the event loop
- 9.2 Modules, configuration and the process
- 9.3 Streams, buffers and events
- 9.4 Core APIs: files, HTTP, crypto and child processes
- 9.5 Express
- 9.6 Fastify, NestJS and other frameworks
- 9.7 Security for Node.js apps
- 9.8 Testing, debugging and tooling
- 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
What is Node.js?
- A document database written entirely in JavaScript
- A browser extension that runs scripts on web pages
- A V8-based runtime for JavaScript outside the browser
- 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.
What is the difference between CommonJS and ES modules in Node.js?
- They're the same module system, just with different file extensions
- CommonJS is the newer standard, and ES modules are the legacy system
- ES modules can't be used in Node.js at all, only in browsers
- 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`.
Why are streams useful for handling large files in Node.js?
- They make the files take up less space on disk
- They make the file read faster than reading at once
- They encrypt the data automatically as it flows
- 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.
What does `fs.readFileSync` do inside an HTTP request handler?
- It reads in a background thread without blocking anything
- It throws an error whenever it's used inside a server
- It caches the file's contents in memory forever
- 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.
What is middleware in Express?
- A routing table stored in a JSON configuration file
- A plugin that extends the V8 engine with new features
- A database access layer that ships built into Express
- 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.
Which is a modern alternative framework to Express with schema-based validation and a focus on performance?
- Mocha
- Fastify
- jQuery
- Lodash
Answer: B. Fastify NestJS is another popular option, adding structure and dependency injection.
What does `helmet` add to an Express app?
- A pooled database connection manager
- Security headers like CSP and HSTS
- Automatic HTTPS certificates from Let's Encrypt
- User authentication and login routes
Answer: B. Security headers like CSP and HSTS It's a quick baseline, not a complete security solution.
Which tool helps diagnose a memory leak in a Node.js process?
- ESLint, with its memory-leak rule set
- `console.log` of every variable in the app
- Heap snapshots compared over time in DevTools
- `npm audit`, which reports leaky packages
Answer: C. Heap snapshots compared over time in DevTools Look for object counts that keep growing between snapshots.
How can a Node.js app use all the CPU cores on one machine?
- Rewrite more of the code to use `async` functions
- Run several processes, via `cluster`, PM2 or containers
- Raise the libuv thread pool size to match the core count
- 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.
Why can one Node.js process handle many concurrent connections?
- It forks a separate child process for every incoming request
- It queues requests and handles each one fully, one at a time
- It quietly starts a new OS thread for every incoming request
- 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.
More Server Side
- HTTP fundamentals
- REST API design
- GraphQL
- gRPC & real-time APIs
- OAuth 2.0, OIDC & JWT
- Sessions, cookies & web app security
- C# & .NET
- Java & Spring Boot
- Python, Django & FastAPI
- Go (Golang)
- Concurrency & multithreading
- OOP & SOLID
- Design patterns
- Dependency injection
- Logging & observability
- Data structures
- Algorithms & Big-O
- Linux & shell scripting