LPI Web Dev Essentials study materials
LPI Web Dev Essentials study resources

LPI Web Dev Essentials: NodeJS Server Programming

LPI Web Dev Essentials · Work through your exam, one topic at a time.

All guide sections

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() and module.exports; ES modules use import and export.
  • Built-in modules include fs, path, http, and the global process object.

npm and package.json

  • dependencies are needed at runtime; devDependencies are only for development.
  • scripts define commands such as npm 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.params holds route segments, req.query holds 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.