HTTP
http.createServer()
Construct an HTTP server; explicitly manage listening, timeouts and shutdown. Local Node 22.16.0; production target compatibility pending. See https://nodejs.org/download/release/v22.16.0/docs/api/http.html.
Formal Syntax & Structure
nodejs syntaxnodejs
http.createServer([options][, requestListener])Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| options | object | Optional server settings. |
| requestListener | function | Incoming request handler. |
Return Value
http.Server
Result or receiver of the documented operation; see the linked versioned API contract.
Working Example
Example Snippetnodejs
import { createServer } from 'node:http';import { once } from 'node:events';async function withServer(handler, use) { const server = createServer({ headersTimeout: 2000, requestTimeout: 2000 }, handler); server.listen(0, '127.0.0.1'); await once(server, 'listening'); try { await use(`http://127.0.0.1:${server.address().port}`); } finally { await new Promise(resolve => { server.close(resolve); server.closeAllConnections(); }); }}const localFetch = (url, options = {}) => fetch(url, { ...options, redirect: 'error', signal: options.signal ?? AbortSignal.timeout(2000)});await withServer((req,res)=>{ res.setHeader('content-type','application/json'); res.end(JSON.stringify([{id:1,title:'Notebook'}]));},async base=>{const r=await localFetch(base+'/catalog'); console.log(r.status,(await r.json())[0].title);});