node:http Serves JSON Without A Framework

Serve JSON with node:http createServer alone: listen(0) takes a free ephemeral port and close releases the handle so the process exits.

JavascriptData Fetching

Code

javascriptsnippet
15 lines
import { createServer } from 'node:http';

const server = createServer((req, res) => {
  // writeHead sets status and headers first; res.end writes the body
  res.writeHead(200, { 'content-type': 'application/json' });
  res.end(JSON.stringify({ status: 'ok', path: req.url }));
});

// Port 0 asks the OS for a free ephemeral port instead of a fixed one
server.listen(0, '127.0.0.1', () => {
  const { port } = server.address();
  console.log('listening:', port > 0);
  // Closing frees the handle so the process can exit on its own
  server.close(() => console.log('closed cleanly'));
});

Output

Captured from a sandboxed run of this snippet in the build pipeline.

listening: true
closed cleanly

What the code does

node:http supplies createServer — built-in surface, no package involved.

Top-level bindings server hold the demo state — nothing sits inside a function scope.

What to watch for

  • The dependency surface is just node:http, and that one is built into Node.js.

Applying it

Expect labeled output — listening:, closed cleanly — when the file runs.

Statements that matter

res.end(JSON.stringify({ status: 'ok', path: req.url }));
server.listen(0, '127.0.0.1', () => {
  const { port } = server.address();
  console.log('listening:', port > 0);
  // Closing frees the handle so the process can exit on its own
  server.close(() => console.log('closed cleanly'));
});

Interactive Tools for This Topic

FAQ

Is the imported module an npm package?
No — `node:http` is built into Node.js. The `node:` prefix marks core modules, so there is nothing to add to a project.