NodeJS Server Programming
NodeJS Server Programming tests the runtime model and the practical building blocks of a server: modules, npm, the http module, and Express routing and middleware.
Runtime and modules
- Node runs JavaScript outside the browser on a single-threaded event loop with non-blocking I/O; long synchronous work blocks every request.
- CommonJS uses
require()andmodule.exports; ES modules useimportandexport. - Built-in modules include
fs,path,http, and the globalprocessobject.
npm and package.json
dependenciesare needed at runtime;devDependenciesare only for development.scriptsdefine commands such asnpm start; the lockfile pins transitive versions.
HTTP and Express
http.createServer((req, res) => {})exposes raw request and response objects;res.end()finishes a response.- Express routes like
app.get('/users/:id', handler);req.paramsholds route segments,req.queryholds the query string. - Middleware runs in order and must call
next()or send a response. express.json()parses JSON bodies;express.static()serves files.
Worked example
app.get('/users/:id', (req, res) => {
const user = users.find(u => u.id === Number(req.params.id));
if (!user) return res.status(404).json({ error: 'not found' });
res.json(user);
});
Reasoning: :id is a route parameter read from req.params.id, and it must be converted because URL values arrive as strings. A missing user returns 404 with a JSON body. The return stops the handler so res.json is not called twice, which would throw ERR_HTTP_HEADERS_SENT.
Traps
Do not block the event loop with fs.readFileSync inside a handler, forget next() in middleware, or register the 404 handler before the routes. Confusing req.params with req.query and sending a response before calling next() are common causes of failing tests.