Nodejs
179 bites tagged Nodejs — interview questions with model answers, and 60-second explainers.
404 vs 500: missing resource vs server failure
A missing resource returns 404 Not Found (client asked for something absent); a database failure returns 500 Internal Server Error (server-side fault). 4xx versus 5xx semantics.
Idempotency: PUT vs POST in REST
Idempotent means repeated identical requests leave the same server state; PUT is idempotent, POST is not. Use PUT to overwrite a resource at a known URL. understanding idempotency.
Modularize routes with express.Router
Create a Router per resource in its own file, define routes on it, export it, and mount with app.use('/products', router). structuring a growing app.
Status codes for successful POST and GET
201 Created for a successful POST (ideally with a Location header), 200 OK for a successful GET returning data. correct 2xx semantics. returning 200 for every success or 204 when a body is sent.
req.params vs req.query vs req.body in Express
Req.params holds named route segments, req.query holds the URL query string, req.body holds the parsed payload. where request data lives. confusing query with params, or expecting req.body without a body parser.
Design an Express route to create a user
POST to a collection URL like /users, read the payload from req.body via express.json(), return 201 with the created resource. REST conventions for creation. using GET to create or putting data in the URL.
Conditionally apply middleware by request property
Use express.text({ type: 'application/xml' }) or a guard wrapper that checks req.is() then calls the parser or next(). knowing helpers and the type option exist.
Write a JWT authentication middleware
Read the header, strip Bearer, jwt.verify with the secret, set req.user and next(), else send 401. extracting a Bearer token, verifying it, and gating access. calling next() after sending 401, or trusting an unverified token.
Middleware execution order and sharing data via req
Middleware runs top-down in registration order; each calls next(); attach data like req.user that later handlers read. the sequential pipeline and shared req object. assuming parallel execution or using globals to pass state.
Express error-handling middleware signature
(err, req, res, next) with err first, identified by arity, placed last after all routes. recognizing the four-argument signature. omitting the err parameter or registering it before the routes it should catch.
Application-level vs router-level middleware
App.use() binds to the app and runs everywhere; router.use() binds to a Router and runs only for that router's routes. scoping of middleware. claiming they are interchangeable or that scope does not matter.
Write a request-logging middleware in Express
Read req.method, log with a timestamp, then call next() to continue. the (req, res, next) signature and calling next(). forgetting next() so the request hangs, or ending the response prematurely.
Parse JSON and URL-encoded bodies in Express
Express.json() for JSON, express.urlencoded() for form data, both registered via app.use(). knowledge of built-in body parsers. reaching for the deprecated body-parser package or forgetting extended option.
Serving static files in Express
App.use with express.static pointing at the public directory, files served relative to that root, often combined with an absolute path. knowing the built-in static middleware.
Minimal Express Hello World server
Import express, create an app, define app.get on the root sending a response, call app.listen on a port. basic Express setup fluency. forgetting app.listen or confusing the require with the app instance.
http.Agent and connection pooling
The agent pools and keeps sockets alive, avoiding repeated TCP and TLS handshakes, controlled by keepAlive and maxSockets. reusing TCP connections for outbound requests. thinking each request always needs a fresh connection.
Backpressure in Node.js streams
Backpressure pauses the readable when the writable buffer fills, pipe and pipeline manage it automatically, pipeline also propagates errors and cleans up. flow control between fast producer and slow consumer.
Scaling across cores with cluster and os
Os.cpus gives core count, the primary forks one worker per core, all workers share the listening port, the OS load-balances connections. scaling single-threaded Node across cores. thinking one Node process uses all cores.
fs.watch vs fs.watchFile
Watch uses OS event notifications, efficient but inconsistent across platforms, watchFile polls stat at an interval, reliable but slower. file change detection mechanisms. not knowing watch is event based versus polling.
path.resolve vs path.join
Join concatenates and normalizes relative segments, resolve builds an absolute path right to left from cwd and resets on any absolute segment. nuance of path construction. treating them as interchangeable.
Reading a POST body from the request stream
Body arrives in chunks via data events, accumulate them, on the end event concatenate and JSON.parse inside try/catch. that req is a readable stream. expecting req.body to exist or parsing before all chunks arrive.
Counting lines in a 5GB log file efficiently
ReadFile loads all 5GB into RAM and may exceed buffer limits, instead stream with createReadStream plus readline and count line by line. streaming versus buffering large data. proposing readFile then split on newlines.
Minimal HTTP server with the http module
CreateServer with a request listener, set status and Content-Type, end the response, call listen on 3000. knowing the raw http API beneath frameworks. forgetting res.end so the connection hangs.
Why use path.join over string concatenation
Path.join uses the correct OS separator, collapses duplicate slashes, normalizes . and .. segments. awareness of cross-platform path handling. hardcoding forward slashes and assuming concatenation always works.
Get Nodejs bites daily.
Five a day, five minutes, offline. With quizzes so it sticks.
Open testing — you’ll join as an early tester.