http
4 methodsServer and client utilities from the http module.
http.createServer(requestListener?) -> http.ServerReturns a new HTTP server that invokes the listener for each request.
Parameters
| Name | Type | Description |
|---|---|---|
| requestListener | (req, res) => void | Function called with IncomingMessage and ServerResponse. |
Returns
http.Server
Example
nodejs
import http from 'node:http';
const server = http.createServer((req, res) => {
res.writeHead(200, { 'content-type': 'text/plain' });
res.end('hello');
});http.request(options, callback?) -> http.ClientRequestInitiates an HTTP request and returns the ClientRequest; emit 'response' or pass a callback.
Parameters
| Name | Type | Description |
|---|---|---|
| options | object | string | URL | { method, hostname, port, path, headers } or URL. |
| callback | (res) => void | Optional response handler. |
Returns
http.ClientRequest
Example
nodejs
import http from 'node:http';
const req = http.request({ hostname: 'localhost', port: 3000, path: '/health', method: 'GET' }, (res) => {
console.log(res.statusCode);
});
req.end();server.listen(port, hostname?, callback?) -> serverStarts listening for connections on the given port and optional hostname.
Parameters
| Name | Type | Description |
|---|---|---|
| port | number | TCP port; 0 picks a random free port. |
| hostname | string | Optional bind address; defaults to all interfaces. |
| callback | () => void | Called once listening has started. |
Returns
http.Server
Example
nodejs
server.listen(3000, '127.0.0.1', () => {
console.log('listening on 3000');
});http.get(options, callback?) -> http.ClientRequestConvenience method for GET requests; auto-calls req.end().
Parameters
| Name | Type | Description |
|---|---|---|
| options | object | string | URL | Request target. |
| callback | (res) => void | Optional response handler. |
Returns
http.ClientRequest
Example
nodejs
http.get('http://localhost:3000/health', (res) => {
res.on('data', (c) => process.stdout.write(c));
});