0
0
mirror of https://github.com/nodejs/node.git synced 2024-12-01 16:10:02 +01:00
nodejs/doc/api/http.md

2446 lines
72 KiB
Markdown
Raw Normal View History

2012-02-27 20:09:33 +01:00
# HTTP
2010-10-28 14:18:16 +02:00
<!--introduced_in=v0.10.0-->
> Stability: 2 - Stable
2010-10-28 14:18:16 +02:00
To use the HTTP server and client one must `require('http')`.
The HTTP interfaces in Node.js are designed to support many features
2010-10-28 14:18:16 +02:00
of the protocol which have been traditionally difficult to use.
In particular, large, possibly chunk-encoded, messages. The interface is
careful to never buffer entire requests or responses, so the
2010-10-28 14:18:16 +02:00
user is able to stream data.
HTTP message headers are represented by an object like this:
<!-- eslint-skip -->
```js
{ 'content-length': '123',
'content-type': 'text/plain',
'connection': 'keep-alive',
'host': 'mysite.com',
'accept': '*/*' }
```
2010-10-28 14:18:16 +02:00
Keys are lowercased. Values are not modified.
In order to support the full spectrum of possible HTTP applications, the Node.js
2010-10-28 14:18:16 +02:00
HTTP API is very low-level. It deals with stream handling and message
parsing only. It parses a message into headers and body but it does not
parse the actual headers or the body.
See [`message.headers`][] for details on how duplicate headers are handled.
2013-08-15 23:12:12 +02:00
The raw headers as they were received are retained in the `rawHeaders`
property, which is an array of `[key, value, key2, value2, ...]`. For
2013-08-15 23:12:12 +02:00
example, the previous message header object might have a `rawHeaders`
list like the following:
<!-- eslint-disable semi -->
```js
[ 'ConTent-Length', '123456',
'content-LENGTH', '123',
'content-type', 'text/plain',
'CONNECTION', 'keep-alive',
'Host', 'mysite.com',
'accepT', '*/*' ]
```
2010-10-28 14:18:16 +02:00
## Class: `http.Agent`
<!-- YAML
added: v0.3.4
-->
2010-10-28 14:18:16 +02:00
An `Agent` is responsible for managing connection persistence
and reuse for HTTP clients. It maintains a queue of pending requests
for a given host and port, reusing a single socket connection for each
until the queue is empty, at which time the socket is either destroyed
or put into a pool where it is kept to be used again for requests to the
same host and port. Whether it is destroyed or pooled depends on the
`keepAlive` [option](#http_new_agent_options).
Pooled connections have TCP Keep-Alive enabled for them, but servers may
still close idle connections, in which case they will be removed from the
pool and a new connection will be made when a new HTTP request is made for
that host and port. Servers may also refuse to allow multiple requests
over the same connection, in which case the connection will have to be
remade for every request and cannot be pooled. The `Agent` will still make
the requests to that server, but each one will occur over a new connection.
When a connection is closed by the client or the server, it is removed
from the pool. Any unused sockets in the pool will be unrefed so as not
to keep the Node.js process running when there are no outstanding requests.
(see [`socket.unref()`][]).
It is good practice, to [`destroy()`][] an `Agent` instance when it is no
longer in use, because unused sockets consume OS resources.
Sockets are removed from an agent when the socket emits either
a `'close'` event or an `'agentRemove'` event. When intending to keep one
HTTP request open for a long time without keeping it in the agent, something
like the following may be done:
2010-10-28 14:18:16 +02:00
```js
http.get(options, (res) => {
// Do stuff
}).on('socket', (socket) => {
socket.emit('agentRemove');
});
```
2010-10-28 14:18:16 +02:00
An agent may also be used for an individual request. By providing
`{agent: false}` as an option to the `http.get()` or `http.request()`
functions, a one-time use `Agent` with default options will be used
for the client connection.
`agent:false`:
2010-10-28 14:18:16 +02:00
```js
http.get({
hostname: 'localhost',
port: 80,
path: '/',
agent: false // Create a new agent just for this one request
}, (res) => {
// Do stuff with response
});
```
2010-10-28 14:18:16 +02:00
### `new Agent([options])`
<!-- YAML
added: v0.3.4
-->
2010-10-28 14:18:16 +02:00
* `options` {Object} Set of configurable options to set on the agent.
Can have the following fields:
* `keepAlive` {boolean} Keep sockets around even when there are no
outstanding requests, so they can be used for future requests without
having to reestablish a TCP connection. Not to be confused with the
`keep-alive` value of the `Connection` header. The `Connection: keep-alive`
header is always sent when using an agent except when the `Connection`
header is explicitly specified or when the `keepAlive` and `maxSockets`
options are respectively set to `false` and `Infinity`, in which case
`Connection: close` will be used. **Default:** `false`.
* `keepAliveMsecs` {number} When using the `keepAlive` option, specifies
the [initial delay](net.html#net_socket_setkeepalive_enable_initialdelay)
for TCP Keep-Alive packets. Ignored when the
`keepAlive` option is `false` or `undefined`. **Default:** `1000`.
* `maxSockets` {number} Maximum number of sockets to allow per
host. Each request will use a new socket until the maximum is reached.
**Default:** `Infinity`.
* `maxFreeSockets` {number} Maximum number of sockets to leave open
in a free state. Only relevant if `keepAlive` is set to `true`.
**Default:** `256`.
* `timeout` {number} Socket timeout in milliseconds.
This will set the timeout when the socket is created.
2010-10-28 14:18:16 +02:00
`options` in [`socket.connect()`][] are also supported.
The default [`http.globalAgent`][] that is used by [`http.request()`][] has all
of these values set to their respective defaults.
To configure any of them, a custom [`http.Agent`][] instance must be created.
```js
const http = require('http');
const keepAliveAgent = new http.Agent({ keepAlive: true });
options.agent = keepAliveAgent;
http.request(options, onResponseCallback);
```
### `agent.createConnection(options[, callback])`
<!-- YAML
added: v0.11.4
-->
* `options` {Object} Options containing connection details. Check
[`net.createConnection()`][] for the format of the options
* `callback` {Function} Callback function that receives the created socket
* Returns: {stream.Duplex}
Produces a socket/stream to be used for HTTP requests.
By default, this function is the same as [`net.createConnection()`][]. However,
custom agents may override this method in case greater flexibility is desired.
A socket/stream can be supplied in one of two ways: by returning the
socket/stream from this function, or by passing the socket/stream to `callback`.
This method is guaranteed to return an instance of the {net.Socket} class,
a subclass of {stream.Duplex}, unless the user specifies a socket
type other than {net.Socket}.
`callback` has a signature of `(err, stream)`.
### `agent.keepSocketAlive(socket)`
<!-- YAML
added: v8.1.0
-->
* `socket` {stream.Duplex}
Called when `socket` is detached from a request and could be persisted by the
`Agent`. Default behavior is to:
```js
socket.setKeepAlive(true, this.keepAliveMsecs);
socket.unref();
return true;
```
This method can be overridden by a particular `Agent` subclass. If this
method returns a falsy value, the socket will be destroyed instead of persisting
it for use with the next request.
The `socket` argument can be an instance of {net.Socket}, a subclass of
{stream.Duplex}.
### `agent.reuseSocket(socket, request)`
<!-- YAML
added: v8.1.0
-->
* `socket` {stream.Duplex}
* `request` {http.ClientRequest}
Called when `socket` is attached to `request` after being persisted because of
the keep-alive options. Default behavior is to:
```js
socket.ref();
```
This method can be overridden by a particular `Agent` subclass.
The `socket` argument can be an instance of {net.Socket}, a subclass of
{stream.Duplex}.
### `agent.destroy()`
<!-- YAML
added: v0.11.4
-->
Destroy any sockets that are currently in use by the agent.
It is usually not necessary to do this. However, if using an
agent with `keepAlive` enabled, then it is best to explicitly shut down
the agent when it will no longer be used. Otherwise,
sockets may hang open for quite a long time before the server
terminates them.
### `agent.freeSockets`
<!-- YAML
added: v0.11.4
-->
2010-10-28 14:18:16 +02:00
* {Object}
An object which contains arrays of sockets currently awaiting use by
the agent when `keepAlive` is enabled. Do not modify.
2010-10-28 14:18:16 +02:00
Sockets in the `freeSockets` list will be automatically destroyed and
removed from the array on `'timeout'`.
### `agent.getName(options)`
<!-- YAML
added: v0.11.4
-->
2010-10-28 14:18:16 +02:00
* `options` {Object} A set of options providing information for name generation
* `host` {string} A domain name or IP address of the server to issue the
request to
* `port` {number} Port of remote server
* `localAddress` {string} Local interface to bind for network connections
when issuing the request
* `family` {integer} Must be 4 or 6 if this doesn't equal `undefined`.
* Returns: {string}
Get a unique name for a set of request options, to determine whether a
connection can be reused. For an HTTP agent, this returns
`host:port:localAddress` or `host:port:localAddress:family`. For an HTTPS agent,
the name includes the CA, cert, ciphers, and other HTTPS/TLS-specific options
that determine socket reusability.
### `agent.maxFreeSockets`
<!-- YAML
added: v0.11.7
-->
* {number}
By default set to 256. For agents with `keepAlive` enabled, this
sets the maximum number of sockets that will be left open in the free
state.
### `agent.maxSockets`
<!-- YAML
added: v0.3.6
-->
* {number}
By default set to `Infinity`. Determines how many concurrent sockets the agent
can have open per origin. Origin is the returned value of [`agent.getName()`][].
### `agent.requests`
<!-- YAML
added: v0.5.9
-->
* {Object}
An object which contains queues of requests that have not yet been assigned to
sockets. Do not modify.
### `agent.sockets`
<!-- YAML
added: v0.3.6
-->
* {Object}
An object which contains arrays of sockets currently in use by the
agent. Do not modify.
## Class: `http.ClientRequest`
<!-- YAML
added: v0.1.17
-->
* Extends: {Stream}
This object is created internally and returned from [`http.request()`][]. It
represents an _in-progress_ request whose header has already been queued. The
header is still mutable using the [`setHeader(name, value)`][],
[`getHeader(name)`][], [`removeHeader(name)`][] API. The actual header will
be sent along with the first data chunk or when calling [`request.end()`][].
To get the response, add a listener for [`'response'`][] to the request object.
[`'response'`][] will be emitted from the request object when the response
headers have been received. The [`'response'`][] event is executed with one
argument which is an instance of [`http.IncomingMessage`][].
During the [`'response'`][] event, one can add listeners to the
response object; particularly to listen for the `'data'` event.
2010-10-28 14:18:16 +02:00
If no [`'response'`][] handler is added, then the response will be
entirely discarded. However, if a [`'response'`][] event handler is added,
then the data from the response object **must** be consumed, either by
calling `response.read()` whenever there is a `'readable'` event, or
by adding a `'data'` handler, or by calling the `.resume()` method.
Until the data is consumed, the `'end'` event will not fire. Also, until
the data is read it will consume memory that can eventually lead to a
'process out of memory' error.
2010-10-28 14:18:16 +02:00
Unlike the `request` object, if the response closes prematurely, the
`response` object does not emit an `'error'` event but instead emits the
`'aborted'` event.
Node.js does not check whether Content-Length and the length of the
body which has been transmitted are equal or not.
### Event: `'abort'`
<!-- YAML
added: v1.4.1
-->
Emitted when the request has been aborted by the client. This event is only
emitted on the first call to `abort()`.
2010-10-28 14:18:16 +02:00
### Event: `'connect'`
<!-- YAML
added: v0.7.0
-->
2010-10-28 14:18:16 +02:00
* `response` {http.IncomingMessage}
* `socket` {stream.Duplex}
* `head` {Buffer}
2010-10-28 14:18:16 +02:00
Emitted each time a server responds to a request with a `CONNECT` method. If
this event is not being listened for, clients receiving a `CONNECT` method will
have their connections closed.
2010-10-28 14:18:16 +02:00
This event is guaranteed to be passed an instance of the {net.Socket} class,
a subclass of {stream.Duplex}, unless the user specifies a socket
type other than {net.Socket}.
A client and server pair demonstrating how to listen for the `'connect'` event:
2010-10-28 14:18:16 +02:00
```js
const http = require('http');
const net = require('net');
const { URL } = require('url');
// Create an HTTP tunneling proxy
const proxy = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('okay');
});
proxy.on('connect', (req, clientSocket, head) => {
// Connect to an origin server
const { port, hostname } = new URL(`http://${req.url}`);
const serverSocket = net.connect(port || 80, hostname, () => {
clientSocket.write('HTTP/1.1 200 Connection Established\r\n' +
'Proxy-agent: Node.js-Proxy\r\n' +
'\r\n');
serverSocket.write(head);
serverSocket.pipe(clientSocket);
clientSocket.pipe(serverSocket);
});
});
// Now that proxy is running
proxy.listen(1337, '127.0.0.1', () => {
// Make a request to a tunneling proxy
const options = {
port: 1337,
host: '127.0.0.1',
method: 'CONNECT',
path: 'www.google.com:80'
};
const req = http.request(options);
req.end();
req.on('connect', (res, socket, head) => {
console.log('got connected!');
// Make a request over an HTTP tunnel
socket.write('GET / HTTP/1.1\r\n' +
'Host: www.google.com:80\r\n' +
'Connection: close\r\n' +
'\r\n');
socket.on('data', (chunk) => {
console.log(chunk.toString());
});
socket.on('end', () => {
proxy.close();
});
});
});
```
### Event: `'continue'`
<!-- YAML
added: v0.3.2
-->
Emitted when the server sends a '100 Continue' HTTP response, usually because
the request contained 'Expect: 100-continue'. This is an instruction that
the client should send the request body.
### Event: `'information'`
<!-- YAML
2018-04-24, Version 10.0.0 (Current) * Assert * Calling `assert.fail()` with more than one argument is deprecated. #70dcacd710 * Calling `assert.ok()` with no arguments will now throw. #3cd7977a42 * Calling `assert.ifError()` will now throw with any argument other than `undefined` or `null`. Previously the method would throw with any truthy value. #e65a6e81ef * The `assert.rejects()` and `assert.doesNotReject()` methods have been added for working with async functions. #599337f43e * Async_hooks * Older experimental async_hooks APIs have been removed. #1cc6b993b9 * Buffer * Uses of `new Buffer()` and `Buffer()` outside of the `node_modules` directory will now emit a runtime deprecation warning. #9d4ab90117 * `Buffer.isEncoding()` now returns `undefined` for falsy values, including an empty string. #452eed956e * `Buffer.fill()` will throw if an attempt is made to fill with an empty `Buffer`. #1e802539b2 * Child Process * Undefined properties of env are ignored. #38ee25e2e2, #85739b6c5b * Console * The `console.table()` method has been added. #97ace04492 * Crypto * The `crypto.createCipher()` and `crypto.createDecipher()` methods have been deprecated. Please use `crypto.createCipheriv()` and `crypto.createDecipheriv()` instead. #81f88e30dd * The `decipher.finaltol()` method has been deprecated. #19f3927d92 * The `crypto.DEFAULT_ENCODING` property has been deprecated. #6035beea93 * The `ECDH.convertKey()` method has been added. #f2e02883e7 * The `crypto.fips` property has been deprecated. #6e7992e8b8 * Dependencies * V8 has been updated to 6.6. #9daebb48d6 * OpenSSL has been updated to 1.1.0h. #66cb29e646 * EventEmitter * The `EventEmitter.prototype.off()` method has been added as an alias for `EventEmitter.prototype.removeListener()`. #3bb6f07d52 * File System * The `fs.promises` API provides experimental promisified versions of the `fs` functions. #329fc78e49 * Invalid path errors are now thrown synchronously. #d8f73385e2 * The `fs.readFile()` method now partitions reads to avoid thread pool exhaustion. #67a4ce1c6e * HTTP * Processing of HTTP Status codes `100`, `102-199` has been improved. #baf8495078 * Multi-byte characters in URL paths are now forbidden. #b961d9fd83 * N-API * The n-api is no longer experimental. #cd7d7b15c1 * Net * The `'close'` event will be emitted after `'end'`. #9b7a6914a7 * Perf_hooks * The `PerformanceObserver` class is now an `AsyncResource` and can be monitored using `async_hooks`. #009e41826f * Trace events are now emitted for performance events. #9e509b622b * The `performance` API has been simplified. #2ec6995555 * Performance milestone marks will be emitted as trace events. #96cb4fb795 * Process * Using non-string values for `process.env` is deprecated. #5826fe4e79 * The `process.assert()` method is deprecated. #703e37cf3f * REPL * REPL now experimentally supports top-level await when using the `--experimental-repl-await` flag. #eeab7bc068 * The previously deprecated "magic mode" has been removed. #4893f70d12 * The previously deprecated `NODE_REPL_HISTORY_FILE` environment variable has been removed. #60c9ad7979 * Proxy objects are shown as Proxy objects when inspected. #90a43906ab * Streams * The `'readable'` event is now always deferred with nextTick. #1e0f3315c7 * A new `pipeline()` method has been provided for building end-to-data stream pipelines. #a5cf3feaf1 * Experimental support for async for-await has been added to `stream.Readable`. #61b4d60c5d * Timers * The `enroll()` and `unenroll()` methods have been deprecated. #68783ae0b8 * TLS * The `tls.convertNONProtocols()` method has been deprecated. #9204a0db6e * Support for NPN (next protocol negotiation) has been dropped. #5bfbe5ceae * The `ecdhCurve` default is now `'auto'`. #af78840b19 * Trace Events * A new `trace_events` top-level module allows trace event categories to be enabled/disabld at runtime. #da5d818a54 * URL * The WHATWG URL API is now a global. #312414662b * Util * `util.types.is[…]` type checks have been added. #b20af8088a * Support for bigint formatting has been added to `util.inspect()`. #39dc947409
2018-03-02 18:53:46 +01:00
added: v10.0.0
-->
* `info` {Object}
* `httpVersion` {string}
* `httpVersionMajor` {integer}
* `httpVersionMinor` {integer}
* `statusCode` {integer}
* `statusMessage` {string}
* `headers` {Object}
* `rawHeaders` {string[]}
Emitted when the server sends a 1xx intermediate response (excluding 101
Upgrade). The listeners of this event will receive an object containing the
HTTP version, status code, status message, key-value headers object,
and array with the raw header names followed by their respective values.
```js
const http = require('http');
const options = {
host: '127.0.0.1',
port: 8080,
path: '/length_request'
};
// Make a request
const req = http.request(options);
req.end();
req.on('information', (info) => {
console.log(`Got information prior to main response: ${info.statusCode}`);
});
```
101 Upgrade statuses do not fire this event due to their break from the
traditional HTTP request/response chain, such as web sockets, in-place TLS
upgrades, or HTTP 2.0. To be notified of 101 Upgrade notices, listen for the
[`'upgrade'`][] event instead.
### Event: `'response'`
<!-- YAML
added: v0.1.0
-->
* `response` {http.IncomingMessage}
Emitted when a response is received to this request. This event is emitted only
once.
### Event: `'socket'`
<!-- YAML
added: v0.5.3
-->
* `socket` {stream.Duplex}
This event is guaranteed to be passed an instance of the {net.Socket} class,
a subclass of {stream.Duplex}, unless the user specifies a socket
type other than {net.Socket}.
### Event: `'timeout'`
<!-- YAML
added: v0.7.8
-->
Emitted when the underlying socket times out from inactivity. This only notifies
that the socket has been idle. The request must be aborted manually.
See also: [`request.setTimeout()`][].
### Event: `'upgrade'`
<!-- YAML
added: v0.1.94
-->
* `response` {http.IncomingMessage}
* `socket` {stream.Duplex}
* `head` {Buffer}
Emitted each time a server responds to a request with an upgrade. If this
event is not being listened for and the response status code is 101 Switching
Protocols, clients receiving an upgrade header will have their connections
closed.
This event is guaranteed to be passed an instance of the {net.Socket} class,
a subclass of {stream.Duplex}, unless the user specifies a socket
type other than {net.Socket}.
A client server pair demonstrating how to listen for the `'upgrade'` event.
```js
const http = require('http');
// Create an HTTP server
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('okay');
});
server.on('upgrade', (req, socket, head) => {
socket.write('HTTP/1.1 101 Web Socket Protocol Handshake\r\n' +
'Upgrade: WebSocket\r\n' +
'Connection: Upgrade\r\n' +
'\r\n');
socket.pipe(socket); // echo back
});
// Now that server is running
server.listen(1337, '127.0.0.1', () => {
// make a request
const options = {
port: 1337,
host: '127.0.0.1',
headers: {
'Connection': 'Upgrade',
'Upgrade': 'websocket'
}
};
const req = http.request(options);
req.end();
req.on('upgrade', (res, socket, upgradeHead) => {
console.log('got upgraded!');
socket.end();
process.exit(0);
});
});
```
### `request.abort()`
<!-- YAML
added: v0.3.8
-->
Marks the request as aborting. Calling this will cause remaining data
in the response to be dropped and the socket to be destroyed.
### `request.aborted`
<!-- YAML
added: v0.11.14
changes:
2018-10-23, Version 11.0.0 (Current) Notable changes: * Build * FreeBSD 10 is no longer supported.[#22617](https://github.com/nodejs/node/pull/22617) * `child_process` * The default value of the `windowsHide` option has been changed to `true`. [#21316](https://github.com/nodejs/node/pull/21316) * `console` * `console.countReset()` will emit a warning if the timer being reset does not exist. [#21649](https://github.com/nodejs/node/pull/21649) * `console.time()` will no longer reset a timer if it already exists. [#20442](https://github.com/nodejs/node/pull/20442) * Dependencies * V8 has been updated to 7.0. [#22754](https://github.com/nodejs/node/pull/22754) * `fs` * The `fs.read()` method now requires a callback. [#22146](https://github.com/nodejs/node/pull/22146) * The previously deprecated `fs.SyncWriteStream` utility has been removed.[#20735](https://github.com/nodejs/node/pull/20735) * `http` * The `http`, `https`, and `tls` modules now use the WHATWG URL parser by default. [#20270](https://github.com/nodejs/node/pull/20270) * General * Use of `process.binding()` has been deprecated. Userland code using `process.binding()` should re-evaluate that use and begin migrating. If there are no supported API alternatives, please open an issue in the Node.js GitHub repository so that a suitable alternative may be discussed. * An experimental implementation of `queueMicrotask()` has been added. [#22951](https://github.com/nodejs/node/pull/22951) * Internal * Windows performance-counter support has been removed. [#22485](https://github.com/nodejs/node/pull/22485) * The `--expose-http2` command-line option has been removed. [#20887](https://github.com/nodejs/node/pull/20887) * Timers * Interval timers will be rescheduled even if previous interval threw an error. [#20002](https://github.com/nodejs/node/pull/20002) * `util` * The WHATWG `TextEncoder` and `TextDecoder` are now globals. [#22281](https://github.com/nodejs/node/pull/22281) * `util.inspect()` output size is limited to 128 MB by default. [#22756](https://github.com/nodejs/node/pull/22756) * A runtime warning will be emitted when `NODE_DEBUG` is set for either `http` or `http2`. [#21914](https://github.com/nodejs/node/pull/21914)
2018-10-03 01:01:19 +02:00
- version: v11.0.0
pr-url: https://github.com/nodejs/node/pull/20230
description: The `aborted` property is no longer a timestamp number.
-->
* {boolean}
The `request.aborted` property will be `true` if the request has
been aborted.
### `request.connection`
<!-- YAML
added: v0.3.0
2019-10-22, Version 13.0.0 (Current) Notable changes: * assert: * If the validation function passed to `assert.throws()` or `assert.rejects()` returns a value other than `true`, an assertion error will be thrown instead of the original error to highlight the programming mistake (Ruben Bridgewater). https://github.com/nodejs/node/pull/28263 * If a constructor function is passed to validate the instance of errors thrown in `assert.throws()` or `assert.reject()`, an assertion error will be thrown instead of the original error (Ruben Bridgewater). https://github.com/nodejs/node/pull/28263 * build: * Node.js releases are now built with default full-icu support. This means that all locales supported by ICU are now included and Intl-related APIs may return different values than before (Richard Lau). https://github.com/nodejs/node/pull/29887 * The minimum Xcode version supported for macOS was increased to 10. It is still possible to build Node.js with Xcode 8 but this may no longer be the case in a future v13.x release (Michael Dawson). https://github.com/nodejs/node/pull/29622 * child_process: * `ChildProcess._channel` (DEP0129) is now a Runtime deprecation (cjihrig). https://github.com/nodejs/node/pull/27949 * console: * The output `console.timeEnd()` and `console.timeLog()` will now automatically select a suitable time unit instead of always using milliseconds (Xavier Stouder). https://github.com/nodejs/node/pull/29251 * deps: * The V8 engine was updated to version 7.8. This includes performance improvements to object destructuring, memory usage and WebAssembly startup time (Myles Borins). https://github.com/nodejs/node/pull/29694) * domain: * The domain's error handler is now executed with the active domain set to the domain's parent to prevent inner recursion (Julien Gilli). https://github.com/nodejs/node/pull/26211 * fs: * The undocumented method `FSWatcher.prototype.start()` was removed (Lucas Holmquist). https://github.com/nodejs/node/pull/29905 * Calling the `open()` method on a `ReadStream` or `WriteStream` now emits a runtime deprecation warning. The methods are supposed to be internal and should not be called by user code (Robert Nagy). https://github.com/nodejs/node/pull/29061 * `fs.read/write`, `fs.readSync/writeSync` and `fd.read/write` now accept any safe integer as their `offset` parameter. The value of `offset` is also no longer coerced, so a valid type must be passed to the functions (Zach Bjornson). https://github.com/nodejs/node/pull/26572 * http: * Aborted requests no longer emit the `end` or `error` events after `aborted` (Robert Nagy). https://github.com/nodejs/node/pull/27984 https://github.com/nodejs/node/pull/20077 * Data will no longer be emitted after a socket error (Robert Nagy). https://github.com/nodejs/node/pull/28711 * The legacy HTTP parser (previously available under the `--http-parser=legacy` flag) was removed (Anna Henningsen). https://github.com/nodejs/node/pull/29589 * The `host` option for HTTP requests is now validated to be a string value (Giorgos Ntemiris). https://github.com/nodejs/node/pull/29568 * The `request.connection` and `response.connection` properties are now runtime deprecated. The equivalent `request.socket` and `response.socket` should be used instead (Robert Nagy). https://github.com/nodejs/node/pull/29015 * http, http2: * The default server timeout was removed (Ali Ijaz Sheikh). https://github.com/nodejs/node/pull/27558 * Brought 425 status code name into accordance with RFC 8470. The name changed from "Unordered Collection" to "Too Early" (Sergei Osipov). https://github.com/nodejs/node/pull/29880 * lib: * The `error.errno` property will now always be a number. To get the string value, use `error.code` instead (Joyee Cheung). https://github.com/nodejs/node/pull/28140 * module: * `module.createRequireFromPath()` is deprecated. Use `module.createRequire()` instead (cjihrig). https://github.com/nodejs/node/pull/27951 * src: * Changing the value of `process.env.TZ` will now clear the tz cache. This affects the default time zone used by methods such as `Date.prototype.toString` (Ben Noordhuis). https://github.com/nodejs/node/pull/20026 * stream: * The timing and behavior of streams was consolidated for a number of edge cases. Please look at the individual commits below for more information. PR-URL: https://github.com/nodejs/node/pull/29504
2019-09-09 14:32:18 +02:00
deprecated: v13.0.0
-->
> Stability: 0 - Deprecated. Use [`request.socket`][].
* {stream.Duplex}
See [`request.socket`][].
### `request.end([data[, encoding]][, callback])`
<!-- YAML
added: v0.1.90
changes:
2018-04-24, Version 10.0.0 (Current) * Assert * Calling `assert.fail()` with more than one argument is deprecated. #70dcacd710 * Calling `assert.ok()` with no arguments will now throw. #3cd7977a42 * Calling `assert.ifError()` will now throw with any argument other than `undefined` or `null`. Previously the method would throw with any truthy value. #e65a6e81ef * The `assert.rejects()` and `assert.doesNotReject()` methods have been added for working with async functions. #599337f43e * Async_hooks * Older experimental async_hooks APIs have been removed. #1cc6b993b9 * Buffer * Uses of `new Buffer()` and `Buffer()` outside of the `node_modules` directory will now emit a runtime deprecation warning. #9d4ab90117 * `Buffer.isEncoding()` now returns `undefined` for falsy values, including an empty string. #452eed956e * `Buffer.fill()` will throw if an attempt is made to fill with an empty `Buffer`. #1e802539b2 * Child Process * Undefined properties of env are ignored. #38ee25e2e2, #85739b6c5b * Console * The `console.table()` method has been added. #97ace04492 * Crypto * The `crypto.createCipher()` and `crypto.createDecipher()` methods have been deprecated. Please use `crypto.createCipheriv()` and `crypto.createDecipheriv()` instead. #81f88e30dd * The `decipher.finaltol()` method has been deprecated. #19f3927d92 * The `crypto.DEFAULT_ENCODING` property has been deprecated. #6035beea93 * The `ECDH.convertKey()` method has been added. #f2e02883e7 * The `crypto.fips` property has been deprecated. #6e7992e8b8 * Dependencies * V8 has been updated to 6.6. #9daebb48d6 * OpenSSL has been updated to 1.1.0h. #66cb29e646 * EventEmitter * The `EventEmitter.prototype.off()` method has been added as an alias for `EventEmitter.prototype.removeListener()`. #3bb6f07d52 * File System * The `fs.promises` API provides experimental promisified versions of the `fs` functions. #329fc78e49 * Invalid path errors are now thrown synchronously. #d8f73385e2 * The `fs.readFile()` method now partitions reads to avoid thread pool exhaustion. #67a4ce1c6e * HTTP * Processing of HTTP Status codes `100`, `102-199` has been improved. #baf8495078 * Multi-byte characters in URL paths are now forbidden. #b961d9fd83 * N-API * The n-api is no longer experimental. #cd7d7b15c1 * Net * The `'close'` event will be emitted after `'end'`. #9b7a6914a7 * Perf_hooks * The `PerformanceObserver` class is now an `AsyncResource` and can be monitored using `async_hooks`. #009e41826f * Trace events are now emitted for performance events. #9e509b622b * The `performance` API has been simplified. #2ec6995555 * Performance milestone marks will be emitted as trace events. #96cb4fb795 * Process * Using non-string values for `process.env` is deprecated. #5826fe4e79 * The `process.assert()` method is deprecated. #703e37cf3f * REPL * REPL now experimentally supports top-level await when using the `--experimental-repl-await` flag. #eeab7bc068 * The previously deprecated "magic mode" has been removed. #4893f70d12 * The previously deprecated `NODE_REPL_HISTORY_FILE` environment variable has been removed. #60c9ad7979 * Proxy objects are shown as Proxy objects when inspected. #90a43906ab * Streams * The `'readable'` event is now always deferred with nextTick. #1e0f3315c7 * A new `pipeline()` method has been provided for building end-to-data stream pipelines. #a5cf3feaf1 * Experimental support for async for-await has been added to `stream.Readable`. #61b4d60c5d * Timers * The `enroll()` and `unenroll()` methods have been deprecated. #68783ae0b8 * TLS * The `tls.convertNONProtocols()` method has been deprecated. #9204a0db6e * Support for NPN (next protocol negotiation) has been dropped. #5bfbe5ceae * The `ecdhCurve` default is now `'auto'`. #af78840b19 * Trace Events * A new `trace_events` top-level module allows trace event categories to be enabled/disabld at runtime. #da5d818a54 * URL * The WHATWG URL API is now a global. #312414662b * Util * `util.types.is[…]` type checks have been added. #b20af8088a * Support for bigint formatting has been added to `util.inspect()`. #39dc947409
2018-03-02 18:53:46 +01:00
- version: v10.0.0
pr-url: https://github.com/nodejs/node/pull/18780
description: This method now returns a reference to `ClientRequest`.
-->
* `data` {string|Buffer}
* `encoding` {string}
* `callback` {Function}
* Returns: {this}
Finishes sending the request. If any parts of the body are
unsent, it will flush them to the stream. If the request is
chunked, this will send the terminating `'0\r\n\r\n'`.
If `data` is specified, it is equivalent to calling
[`request.write(data, encoding)`][] followed by `request.end(callback)`.
If `callback` is specified, it will be called when the request stream
is finished.
### `request.finished`
<!-- YAML
added: v0.0.1
2019-12-17, Version 13.4.0 (Current) This is a security release. For more details about the vulnerability please consult the npm blog: https://blog.npmjs.org/post/189618601100/binary-planting-with-the-npm-cli Notable Changes: * deps: * update npm to 6.13.4 https://github.com/nodejs/node/pull/30904 * update uvwasi (Anna Henningsen) https://github.com/nodejs/node/pull/30745 * upgrade to libuv 1.34.0 (Colin Ihrig) https://github.com/nodejs/node/pull/30783 * doc: * docs deprecate http finished (Robert Nagy) https://github.com/nodejs/node/pull/28679 * events: * add captureRejection option (Matteo Collina) https://github.com/nodejs/node/pull/27867 * http: * add captureRejection support (Matteo Collina) https://github.com/nodejs/node/pull/27867 * llhttp opt-in insecure HTTP header parsing (Sam Roberts) https://github.com/nodejs/node/pull/30567 * http2: * implement capture rection for 'request' and 'stream' events (Matteo Collina) https://github.com/nodejs/node/pull/27867 * net: * implement capture rejections for 'connection' event (Matteo Collina) https://github.com/nodejs/node/pull/27867 * repl: * support previews by eager evaluating input (Ruben Bridgewater) https://github.com/nodejs/node/pull/30811 * stream: * add support for captureRejection option (Matteo Collina) https://github.com/nodejs/node/pull/27867 * tls: * implement capture rejections for 'secureConnection' event (Matteo Collina) https://github.com/nodejs/node/pull/27867 * expose IETF name for current cipher suite (Sam Roberts) https://github.com/nodejs/node/pull/30637 * worker: * add argv constructor option (legendecas) https://github.com/nodejs/node/pull/30559 PR-URL: https://github.com/nodejs/node/pull/30937
2019-12-13 17:02:36 +01:00
deprecated: v13.4.0
-->
> Stability: 0 - Deprecated. Use [`request.writableEnded`][].
* {boolean}
The `request.finished` property will be `true` if [`request.end()`][]
has been called. `request.end()` will automatically be called if the
request was initiated via [`http.get()`][].
### `request.flushHeaders()`
<!-- YAML
added: v1.6.0
-->
Flushes the request headers.
For efficiency reasons, Node.js normally buffers the request headers until
`request.end()` is called or the first chunk of request data is written. It
then tries to pack the request headers and data into a single TCP packet.
That's usually desired (it saves a TCP round-trip), but not when the first
data is not sent until possibly much later. `request.flushHeaders()` bypasses
the optimization and kickstarts the request.
### `request.getHeader(name)`
<!-- YAML
added: v1.6.0
-->
* `name` {string}
* Returns: {any}
Reads out a header on the request. The name is case-insensitive.
The type of the return value depends on the arguments provided to
[`request.setHeader()`][].
```js
request.setHeader('content-type', 'text/html');
request.setHeader('Content-Length', Buffer.byteLength(body));
request.setHeader('Cookie', ['type=ninja', 'language=javascript']);
const contentType = request.getHeader('Content-Type');
// 'contentType' is 'text/html'
const contentLength = request.getHeader('Content-Length');
// 'contentLength' is of type number
const cookie = request.getHeader('Cookie');
// 'cookie' is of type string[]
```
### `request.maxHeadersCount`
* {number} **Default:** `2000`
Limits maximum response headers count. If set to 0, no limit will be applied.
### `request.path`
<!-- YAML
added: v0.4.0
-->
* {string} The request path.
### `request.removeHeader(name)`
<!-- YAML
added: v1.6.0
-->
* `name` {string}
Removes a header that's already defined into headers object.
```js
request.removeHeader('Content-Type');
```
### `request.reusedSocket`
<!-- YAML
2019-10-22, Version 13.0.0 (Current) Notable changes: * assert: * If the validation function passed to `assert.throws()` or `assert.rejects()` returns a value other than `true`, an assertion error will be thrown instead of the original error to highlight the programming mistake (Ruben Bridgewater). https://github.com/nodejs/node/pull/28263 * If a constructor function is passed to validate the instance of errors thrown in `assert.throws()` or `assert.reject()`, an assertion error will be thrown instead of the original error (Ruben Bridgewater). https://github.com/nodejs/node/pull/28263 * build: * Node.js releases are now built with default full-icu support. This means that all locales supported by ICU are now included and Intl-related APIs may return different values than before (Richard Lau). https://github.com/nodejs/node/pull/29887 * The minimum Xcode version supported for macOS was increased to 10. It is still possible to build Node.js with Xcode 8 but this may no longer be the case in a future v13.x release (Michael Dawson). https://github.com/nodejs/node/pull/29622 * child_process: * `ChildProcess._channel` (DEP0129) is now a Runtime deprecation (cjihrig). https://github.com/nodejs/node/pull/27949 * console: * The output `console.timeEnd()` and `console.timeLog()` will now automatically select a suitable time unit instead of always using milliseconds (Xavier Stouder). https://github.com/nodejs/node/pull/29251 * deps: * The V8 engine was updated to version 7.8. This includes performance improvements to object destructuring, memory usage and WebAssembly startup time (Myles Borins). https://github.com/nodejs/node/pull/29694) * domain: * The domain's error handler is now executed with the active domain set to the domain's parent to prevent inner recursion (Julien Gilli). https://github.com/nodejs/node/pull/26211 * fs: * The undocumented method `FSWatcher.prototype.start()` was removed (Lucas Holmquist). https://github.com/nodejs/node/pull/29905 * Calling the `open()` method on a `ReadStream` or `WriteStream` now emits a runtime deprecation warning. The methods are supposed to be internal and should not be called by user code (Robert Nagy). https://github.com/nodejs/node/pull/29061 * `fs.read/write`, `fs.readSync/writeSync` and `fd.read/write` now accept any safe integer as their `offset` parameter. The value of `offset` is also no longer coerced, so a valid type must be passed to the functions (Zach Bjornson). https://github.com/nodejs/node/pull/26572 * http: * Aborted requests no longer emit the `end` or `error` events after `aborted` (Robert Nagy). https://github.com/nodejs/node/pull/27984 https://github.com/nodejs/node/pull/20077 * Data will no longer be emitted after a socket error (Robert Nagy). https://github.com/nodejs/node/pull/28711 * The legacy HTTP parser (previously available under the `--http-parser=legacy` flag) was removed (Anna Henningsen). https://github.com/nodejs/node/pull/29589 * The `host` option for HTTP requests is now validated to be a string value (Giorgos Ntemiris). https://github.com/nodejs/node/pull/29568 * The `request.connection` and `response.connection` properties are now runtime deprecated. The equivalent `request.socket` and `response.socket` should be used instead (Robert Nagy). https://github.com/nodejs/node/pull/29015 * http, http2: * The default server timeout was removed (Ali Ijaz Sheikh). https://github.com/nodejs/node/pull/27558 * Brought 425 status code name into accordance with RFC 8470. The name changed from "Unordered Collection" to "Too Early" (Sergei Osipov). https://github.com/nodejs/node/pull/29880 * lib: * The `error.errno` property will now always be a number. To get the string value, use `error.code` instead (Joyee Cheung). https://github.com/nodejs/node/pull/28140 * module: * `module.createRequireFromPath()` is deprecated. Use `module.createRequire()` instead (cjihrig). https://github.com/nodejs/node/pull/27951 * src: * Changing the value of `process.env.TZ` will now clear the tz cache. This affects the default time zone used by methods such as `Date.prototype.toString` (Ben Noordhuis). https://github.com/nodejs/node/pull/20026 * stream: * The timing and behavior of streams was consolidated for a number of edge cases. Please look at the individual commits below for more information. PR-URL: https://github.com/nodejs/node/pull/29504
2019-09-09 14:32:18 +02:00
added: v13.0.0
-->
* {boolean} Whether the request is send through a reused socket.
When sending request through a keep-alive enabled agent, the underlying socket
might be reused. But if server closes connection at unfortunate time, client
may run into a 'ECONNRESET' error.
```js
const http = require('http');
// Server has a 5 seconds keep-alive timeout by default
http
.createServer((req, res) => {
res.write('hello\n');
res.end();
})
.listen(3000);
setInterval(() => {
// Adapting a keep-alive agent
http.get('http://localhost:3000', { agent }, (res) => {
res.on('data', (data) => {
// Do nothing
});
});
}, 5000); // Sending request on 5s interval so it's easy to hit idle timeout
```
By marking a request whether it reused socket or not, we can do
automatic error retry base on it.
```js
const http = require('http');
const agent = new http.Agent({ keepAlive: true });
function retriableRequest() {
const req = http
.get('http://localhost:3000', { agent }, (res) => {
// ...
})
.on('error', (err) => {
// Check if retry is needed
if (req.reusedSocket && err.code === 'ECONNRESET') {
retriableRequest();
}
});
}
retriableRequest();
```
### `request.setHeader(name, value)`
<!-- YAML
added: v1.6.0
-->
* `name` {string}
* `value` {any}
Sets a single header value for headers object. If this header already exists in
the to-be-sent headers, its value will be replaced. Use an array of strings
here to send multiple headers with the same name. Non-string values will be
stored without modification. Therefore, [`request.getHeader()`][] may return
non-string values. However, the non-string values will be converted to strings
for network transmission.
```js
request.setHeader('Content-Type', 'application/json');
```
or
```js
request.setHeader('Cookie', ['type=ninja', 'language=javascript']);
```
### `request.setNoDelay([noDelay])`
<!-- YAML
added: v0.5.9
-->
* `noDelay` {boolean}
Once a socket is assigned to this request and is connected
[`socket.setNoDelay()`][] will be called.
2010-10-28 14:18:16 +02:00
### `request.setSocketKeepAlive([enable][, initialDelay])`
<!-- YAML
added: v0.5.9
-->
* `enable` {boolean}
* `initialDelay` {number}
Once a socket is assigned to this request and is connected
[`socket.setKeepAlive()`][] will be called.
2010-10-28 14:18:16 +02:00
### `request.setTimeout(timeout[, callback])`
<!-- YAML
added: v0.5.9
changes:
- version: v9.0.0
pr-url: https://github.com/nodejs/node/pull/8895
description: Consistently set socket timeout only when the socket connects.
-->
2010-10-28 14:18:16 +02:00
* `timeout` {number} Milliseconds before a request times out.
* `callback` {Function} Optional function to be called when a timeout occurs.
Same as binding to the `'timeout'` event.
* Returns: {http.ClientRequest}
Once a socket is assigned to this request and is connected
[`socket.setTimeout()`][] will be called.
### `request.socket`
<!-- YAML
added: v0.3.0
-->
* {stream.Duplex}
Reference to the underlying socket. Usually users will not want to access
this property. In particular, the socket will not emit `'readable'` events
because of how the protocol parser attaches to the socket. The `socket`
may also be accessed via `request.connection`.
```js
const http = require('http');
const options = {
host: 'www.google.com',
};
const req = http.get(options);
req.end();
req.once('response', (res) => {
const ip = req.socket.localAddress;
const port = req.socket.localPort;
console.log(`Your IP address is ${ip} and your source port is ${port}.`);
// Consume response object
});
```
This property is guaranteed to be an instance of the {net.Socket} class,
a subclass of {stream.Duplex}, unless the user specified a socket
type other than {net.Socket}.
### `request.writableEnded`
<!-- YAML
2019-08-20, Version 12.9.0 (Current) Notable changes: * crypto: * Added an oaepHash option to asymmetric encryption which allows users to specify a hash function when using OAEP padding. https://github.com/nodejs/node/pull/28335 * deps: * Updated V8 to 7.6.303.29. https://github.com/nodejs/node/pull/28955 * Improves the performance of various APIs such as `JSON.parse` and methods called on frozen arrays. * Adds the Promise.allSettled method. * Improves support of `BigInt` in `Intl` methods. * For more information: https://v8.dev/blog/v8-release-76 * Updated libuv to 1.31.0. https://github.com/nodejs/node/pull/29070 * `UV_FS_O_FILEMAP` has been added for faster access to memory mapped files on Windows. * `uv_fs_mkdir()` now returns `UV_EINVAL` for invalid filenames on Windows. It previously returned `UV_ENOENT`. * The `uv_fs_statfs()` API has been added. * The `uv_os_environ()` and `uv_os_free_environ()` APIs have been added. * fs: * Added `fs.writev`, `fs.writevSync` and `filehandle.writev` (promise version) methods. They allow to write an array of `ArrayBufferView`s to a file descriptor. https://github.com/nodejs/node/pull/25925 https://github.com/nodejs/node/pull/29186 * http: * Added three properties to `OutgoingMessage.prototype`: `writableObjectMode`, `writableLength` and `writableHighWaterMark` https://github.com/nodejs/node/pull/29018 * stream: * Added an new property `readableEnded` to readable streams. Its value is set to `true` when the `'end'` event is emitted. https://github.com/nodejs/node/pull/28814 * Added an new property `writableEnded` to writable streams. Its value is set to `true` after `writable.end()` has been called. https://github.com/nodejs/node/pull/28934 PR-URL: https://github.com/nodejs/node/pull/29210
2019-08-19 21:14:22 +02:00
added: v12.9.0
-->
* {boolean}
Is `true` after [`request.end()`][] has been called. This property
does not indicate whether the data has been flushed, for this use
[`request.writableFinished`][] instead.
### `request.writableFinished`
<!-- YAML
added: v12.7.0
-->
* {boolean}
Is `true` if all data has been flushed to the underlying system, immediately
before the [`'finish'`][] event is emitted.
### `request.write(chunk[, encoding][, callback])`
<!-- YAML
added: v0.1.29
-->
2010-10-28 14:18:16 +02:00
* `chunk` {string|Buffer}
* `encoding` {string}
* `callback` {Function}
* Returns: {boolean}
Sends a chunk of the body. By calling this method
many times, a request body can be sent to a
server. In that case, it is suggested to use the
`['Transfer-Encoding', 'chunked']` header line when
creating the request.
The `encoding` argument is optional and only applies when `chunk` is a string.
Defaults to `'utf8'`.
2010-10-28 14:18:16 +02:00
The `callback` argument is optional and will be called when this chunk of data
is flushed, but only if the chunk is non-empty.
2010-10-28 14:18:16 +02:00
Returns `true` if the entire data was flushed successfully to the kernel
buffer. Returns `false` if all or part of the data was queued in user memory.
`'drain'` will be emitted when the buffer is free again.
2010-10-28 14:18:16 +02:00
When `write` function is called with empty string or buffer, it does
nothing and waits for more input.
## Class: `http.Server`
<!-- YAML
added: v0.1.17
-->
2010-10-28 14:18:16 +02:00
* Extends: {net.Server}
2010-10-28 14:18:16 +02:00
### Event: `'checkContinue'`
<!-- YAML
added: v0.3.0
-->
2010-10-28 14:18:16 +02:00
* `request` {http.IncomingMessage}
* `response` {http.ServerResponse}
2010-10-28 14:18:16 +02:00
Emitted each time a request with an HTTP `Expect: 100-continue` is received.
If this event is not listened for, the server will automatically respond
with a `100 Continue` as appropriate.
2010-10-28 14:18:16 +02:00
Handling this event involves calling [`response.writeContinue()`][] if the
client should continue to send the request body, or generating an appropriate
HTTP response (e.g. 400 Bad Request) if the client should not continue to send
the request body.
2010-10-28 14:18:16 +02:00
When this event is emitted and handled, the [`'request'`][] event will
not be emitted.
### Event: `'checkExpectation'`
<!-- YAML
added: v5.5.0
-->
* `request` {http.IncomingMessage}
* `response` {http.ServerResponse}
Emitted each time a request with an HTTP `Expect` header is received, where the
value is not `100-continue`. If this event is not listened for, the server will
automatically respond with a `417 Expectation Failed` as appropriate.
When this event is emitted and handled, the [`'request'`][] event will
not be emitted.
### Event: `'clientError'`
<!-- YAML
added: v0.1.94
changes:
- version: v6.0.0
pr-url: https://github.com/nodejs/node/pull/4557
description: The default action of calling `.destroy()` on the `socket`
will no longer take place if there are listeners attached
for `'clientError'`.
2019-01-10 Version 9.4.0 (Current) Notable change: * async_hooks: - deprecate AsyncHooks Sensitive API and runInAsyncIdScope. Neither API were documented. (Andreas Madsen) https://github.com/nodejs/node/pull/16972 * deps: - update nghttp2 to 1.29.0 (James M Snell) https://github.com/nodejs/node/pull/17908 - upgrade npm to 5.6.0 (Kat Marchán) https://github.com/nodejs/node/pull/17535 - cherry-pick 50f7455 from upstream V8 (Michaël Zasso) https://github.com/nodejs/node/pull/16591 * events: - remove reaches into _events internals (Anatoli Papirovski) https://github.com/nodejs/node/pull/17440 * http: - add rawPacket in err of `clientError` event (XadillaX) https://github.com/nodejs/node/pull/17672 * http2: - implement maxSessionMemory (James M Snell) https://github.com/nodejs/node/pull/17967 - add initial support for originSet (James M Snell) https://github.com/nodejs/node/pull/17935 - add altsvc support (James M Snell) https://github.com/nodejs/node/pull/17917 - perf_hooks integration (James M Snell) https://github.com/nodejs/node/pull/17906 - Refactoring and cleanup of Http2Session and Http2Stream destroy (James M Snell) https://github.com/nodejs/node/pull/17406 * net: - remove Socket.prototype.write (Anna Henningsen) https://github.com/nodejs/node/pull/17644 - remove Socket.prototype.listen (Ruben Bridgewater) https://github.com/nodejs/node/pull/13735 * repl: - show lexically scoped vars in tab completion (Michaël Zasso) https://github.com/nodejs/node/pull/16591 * stream: - rm {writeable/readable}State.length (Calvin Metcalf) https://github.com/nodejs/node/pull/12857 - add flow and buffer properties to streams (Calvin Metcalf) https://github.com/nodejs/node/pull/12855 * util: - allow wildcards in NODE_DEBUG variable (Tyler) https://github.com/nodejs/node/pull/17609 * zlib: - add ArrayBuffer support (Jem Bezooyen) https://github.com/nodejs/node/pull/16042 * Addedew collaborator** - [starkwang](https://github.com/starkwang) Weijia Wang * Addedew TSC member** - [danbev](https://github.com/danbev) Daniel Bevenius PR-URL: https://github.com/nodejs/node/pull/18069
2018-01-10 01:23:55 +01:00
- version: v9.4.0
pr-url: https://github.com/nodejs/node/pull/17672
description: The `rawPacket` is the current buffer that just parsed. Adding
this buffer to the error object of `'clientError'` event is to
make it possible that developers can log the broken packet.
2019-04-23, Version 12.0.0 (Current) Notable changes: * assert: * validate required arguments (Ruben Bridgewater) [#26641](https://github.com/nodejs/node/pull/26641) * adjust loose assertions (Ruben Bridgewater) [#25008](https://github.com/nodejs/node/pull/25008) * async_hooks: * remove deprecated `emitBefore` and `emitAfter` (Matteo Collina) [#26530](https://github.com/nodejs/node/pull/26530) * remove promise object from resource (Andreas Madsen) [#23443](https://github.com/nodejs/node/pull/23443) * bootstrap: make Buffer and process non-enumerable (Ruben Bridgewater) [#24874](https://github.com/nodejs/node/pull/24874) * buffer: * use stricter range checks (Ruben Bridgewater) [#27045](https://github.com/nodejs/node/pull/27045) * harden `SlowBuffer` creation (ZYSzys) [#26272](https://github.com/nodejs/node/pull/26272) * harden validation of buffer allocation size (ZYSzys) [#26162](https://github.com/nodejs/node/pull/26162) * do proper error propagation in addon methods (Anna Henningsen) [#23939](https://github.com/nodejs/node/pull/23939) * child_process: * remove `options.customFds` (cjihrig) [#25279](https://github.com/nodejs/node/pull/25279) * harden fork arguments validation (ZYSzys) [#27039](https://github.com/nodejs/node/pull/27039) * use non-infinite `maxBuffer` defaults (kohta ito) [#23027](https://github.com/nodejs/node/pull/23027) * console: * don't use ANSI escape codes when `TERM=dumb` (Vladislav Kaminsky) [#26261](https://github.com/nodejs/node/pull/26261) * crypto: * remove legacy native handles (Tobias Nießen) [#27011](https://github.com/nodejs/node/pull/27011) * decode missing passphrase errors (Tobias Nießen) [#25208](https://github.com/nodejs/node/pull/25208) * remove `Cipher.setAuthTag()` and `Decipher.getAuthTag()` (Tobias Nießen) [#26249](https://github.com/nodejs/node/pull/26249) * remove deprecated `crypto._toBuf()` (Tobias Nießen) [#25338](https://github.com/nodejs/node/pull/25338) * set `DEFAULT\_ENCODING` property to non-enumerable (Antoine du Hamel) [#23222](https://github.com/nodejs/node/pull/23222) * deps: * update V8 to 7.4.288.13 (Michaël Zasso, cjihrig, Refael Ackermann) (Anna Henningsen, Ujjwal Sharma) [#26685](https://github.com/nodejs/node/pull/26685) * bump minimum icu version to 63 (Ujjwal Sharma) [#25852](https://github.com/nodejs/node/pull/25852) * update OpenSSL to 1.1.1b (Sam Roberts, Shigeki Ohtsu) [#26327](https://github.com/nodejs/node/pull/26327) * errors: * update error name (Ruben Bridgewater) [#26738](https://github.com/nodejs/node/pull/26738) * fs: * use proper .destroy() implementation for SyncWriteStream (Matteo Collina) [#26690](https://github.com/nodejs/node/pull/26690) * improve mode validation (Ruben Bridgewater) [#26575](https://github.com/nodejs/node/pull/26575) * harden validation of start option in `createWriteStream()` (ZYSzys) [#25579](https://github.com/nodejs/node/pull/25579) * make writeFile consistent with readFile wrt fd (Sakthipriyan Vairamani (thefourtheye)) [#23709](https://github.com/nodejs/node/pull/23709) * http: * validate timeout in `ClientRequest()` (cjihrig) [#26214](https://github.com/nodejs/node/pull/26214) * return HTTP 431 on `HPE_HEADER_OVERFLOW` error (Albert Still) [#25605](https://github.com/nodejs/node/pull/25605) * switch default parser to llhttp (Anna Henningsen) [#24870](https://github.com/nodejs/node/pull/24870) * Runtime-deprecate `outgoingMessage._headers` and `outgoingMessage._headerNames` (Morgan Roderick) [#24167](https://github.com/nodejs/node/pull/24167) * lib: * remove `Atomics.wake()` (Gus Caplan) [#27033](https://github.com/nodejs/node/pull/27033) * move DTRACE\_\* probes out of global scope (James M Snell) [#26541](https://github.com/nodejs/node/pull/26541) * deprecate `_stream_wrap` (Sam Roberts) [#26245](https://github.com/nodejs/node/pull/26245) * use ES6 class inheritance style (Ruben Bridgewater) [#24755](https://github.com/nodejs/node/pull/24755) * module: * remove unintended access to deps/ (Anna Henningsen) [#25138](https://github.com/nodejs/node/pull/25138) * improve error message for MODULE\_NOT\_FOUND (Ali Ijaz Sheikh) [#25690](https://github.com/nodejs/node/pull/25690) * requireStack property for MODULE\_NOT\_FOUND (Ali Ijaz Sheikh) [#25690](https://github.com/nodejs/node/pull/25690) * remove dead code (Ruben Bridgewater) [#26983](https://github.com/nodejs/node/pull/26983) * make `require('.')` never resolve outside the current directory (Ruben Bridgewater) [#26973](https://github.com/nodejs/node/pull/26973) * throw an error for invalid package.json main entries (Ruben Bridgewater) [#26823](https://github.com/nodejs/node/pull/26823) * don't search in `require.resolve.paths` (cjihrig) [#23683](https://github.com/nodejs/node/pull/23683) * net: * remove `Server.listenFD()` (cjihrig) [#27127](https://github.com/nodejs/node/pull/27127) * do not add `.host` and `.port` properties to DNS error (Ruben Bridgewater) [#26751](https://github.com/nodejs/node/pull/26751) * emit "write after end" errors in the next tick (Ouyang Yadong) [#24457](https://github.com/nodejs/node/pull/24457) * deprecate `_setSimultaneousAccepts()` undocumented function (James M Snell) [#23760](https://github.com/nodejs/node/pull/23760) * os: * implement `os.type()` using `uv_os_uname()` (cjihrig) [#25659](https://github.com/nodejs/node/pull/25659) * remove `os.getNetworkInterfaces()` (cjihrig) [#25280](https://github.com/nodejs/node/pull/25280) * process: * make global.process, global.Buffer getters (Guy Bedford) [#26882](https://github.com/nodejs/node/pull/26882) * move DEP0062 (node --debug) to end-of-life (Joyee Cheung) [#25828](https://github.com/nodejs/node/pull/25828) * exit on --debug and --debug-brk after option parsing (Joyee Cheung) [#25828](https://github.com/nodejs/node/pull/25828) * improve `--redirect-warnings` handling (Ruben Bridgewater) [#24965](https://github.com/nodejs/node/pull/24965) * readline: * support TERM=dumb (Vladislav Kaminsky) [#26261](https://github.com/nodejs/node/pull/26261) * repl: * add welcome message (gengjiawen) [#25947](https://github.com/nodejs/node/pull/25947) * fix terminal default setting (Ruben Bridgewater) [#26518](https://github.com/nodejs/node/pull/26518) * check colors with `.getColorDepth()` (Vladislav Kaminsky) [#26261](https://github.com/nodejs/node/pull/26261) * deprecate REPLServer.rli (Ruben Bridgewater) [#26260](https://github.com/nodejs/node/pull/26260) * src: * remove unused `INT_MAX` constant (Sam Roberts) [#27078](https://github.com/nodejs/node/pull/27078) * update `NODE_MODULE_VERSION` to 72 (Ujjwal Sharma) [#26685](https://github.com/nodejs/node/pull/26685) * remove `AddPromiseHook()` (Anna Henningsen) [#26574](https://github.com/nodejs/node/pull/26574) * clean up `MultiIsolatePlatform` interface (Anna Henningsen) [#26384](https://github.com/nodejs/node/pull/26384) * properly configure default heap limits (Ali Ijaz Sheikh) [#25576](https://github.com/nodejs/node/pull/25576) * remove `icuDataDir` from node config (GauthamBanasandra) [#24780](https://github.com/nodejs/node/pull/24780) * tls: * support TLSv1.3 (Sam Roberts) [#26209](https://github.com/nodejs/node/pull/26209) * return correct version from `getCipher()` (Sam Roberts) [#26625](https://github.com/nodejs/node/pull/26625) * check arg types of renegotiate() (Sam Roberts) [#25876](https://github.com/nodejs/node/pull/25876) * add code for `ERR_TLS_INVALID_PROTOCOL_METHOD` (Sam Roberts) [#24729](https://github.com/nodejs/node/pull/24729) * emit a warning when servername is an IP address (Rodger Combs) [#23329](https://github.com/nodejs/node/pull/23329) * disable TLS v1.0 and v1.1 by default (Ben Noordhuis) [#23814](https://github.com/nodejs/node/pull/23814) * remove unused arg to createSecureContext() (Sam Roberts) [#24241](https://github.com/nodejs/node/pull/24241) * deprecate `Server.prototype.setOptions()` (cjihrig) [#23820](https://github.com/nodejs/node/pull/23820) * load `NODE_EXTRA_CA_CERTS` at startup (Ouyang Yadong) [#23354](https://github.com/nodejs/node/pull/23354) * util: * remove `util.print()`, `util.puts()`, `util.debug()` and `util.error()` (cjihrig) [#25377](https://github.com/nodejs/node/pull/25377) * change inspect compact and breakLength default (Ruben Bridgewater) [#27109](https://github.com/nodejs/node/pull/27109) * improve inspect edge cases (Ruben Bridgewater) [#27109](https://github.com/nodejs/node/pull/27109) * only the first line of the error message (Simon Zünd) [#26685](https://github.com/nodejs/node/pull/26685) * don't set the prototype of callbackified functions (Ruben Bridgewater) [#26893](https://github.com/nodejs/node/pull/26893) * rename callbackified function (Ruben Bridgewater) [#26893](https://github.com/nodejs/node/pull/26893) * increase function length when using `callbackify()` (Ruben Bridgewater) [#26893](https://github.com/nodejs/node/pull/26893) * prevent tampering with internals in `inspect()` (Ruben Bridgewater) [#26577](https://github.com/nodejs/node/pull/26577) * prevent Proxy traps being triggered by `.inspect()` (Ruben Bridgewater) [#26241](https://github.com/nodejs/node/pull/26241) * prevent leaking internal properties (Ruben Bridgewater) [#24971](https://github.com/nodejs/node/pull/24971) * protect against monkeypatched Object prototype for inspect() (Rich Trott) [#25953](https://github.com/nodejs/node/pull/25953) * treat format arguments equally (Roman Reiss) [#23162](https://github.com/nodejs/node/pull/23162) * win, fs: * detect if symlink target is a directory (Bartosz Sosnowski) [#23724](https://github.com/nodejs/node/pull/23724) * zlib: * throw TypeError if callback is missing (Anna Henningsen) [#24929](https://github.com/nodejs/node/pull/24929) * make “bare” constants un-enumerable (Anna Henningsen) [#24824](https://github.com/nodejs/node/pull/24824) PR-URL: https://github.com/nodejs/node/pull/26930
2019-03-22 14:19:46 +01:00
- version: v12.0.0
pr-url: https://github.com/nodejs/node/pull/25605
description: The default behavior will return a 431 Request Header
Fields Too Large if a HPE_HEADER_OVERFLOW error occurs.
-->
* `exception` {Error}
* `socket` {stream.Duplex}
2010-10-28 14:18:16 +02:00
If a client connection emits an `'error'` event, it will be forwarded here.
Listener of this event is responsible for closing/destroying the underlying
socket. For example, one may wish to more gracefully close the socket with a
custom HTTP response instead of abruptly severing the connection.
This event is guaranteed to be passed an instance of the {net.Socket} class,
a subclass of {stream.Duplex}, unless the user specifies a socket
type other than {net.Socket}.
Default behavior is to try close the socket with a HTTP '400 Bad Request',
or a HTTP '431 Request Header Fields Too Large' in the case of a
[`HPE_HEADER_OVERFLOW`][] error. If the socket is not writable it is
immediately destroyed.
`socket` is the [`net.Socket`][] object that the error originated from.
2010-10-28 14:18:16 +02:00
```js
const http = require('http');
const server = http.createServer((req, res) => {
res.end();
});
server.on('clientError', (err, socket) => {
socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
});
server.listen(8000);
```
When the `'clientError'` event occurs, there is no `request` or `response`
object, so any HTTP response sent, including response headers and payload,
*must* be written directly to the `socket` object. Care must be taken to
ensure the response is a properly formatted HTTP response message.
`err` is an instance of `Error` with two extra columns:
* `bytesParsed`: the bytes count of request packet that Node.js may have parsed
correctly;
* `rawPacket`: the raw packet of current request.
### Event: `'close'`
<!-- YAML
added: v0.1.4
-->
2010-10-28 14:18:16 +02:00
Emitted when the server closes.
### Event: `'connect'`
<!-- YAML
added: v0.7.0
-->
2011-01-21 02:54:59 +01:00
* `request` {http.IncomingMessage} Arguments for the HTTP request, as it is in
the [`'request'`][] event
* `socket` {stream.Duplex} Network socket between the server and client
* `head` {Buffer} The first packet of the tunneling stream (may be empty)
2011-01-21 02:54:59 +01:00
Emitted each time a client requests an HTTP `CONNECT` method. If this event is
not listened for, then clients requesting a `CONNECT` method will have their
connections closed.
This event is guaranteed to be passed an instance of the {net.Socket} class,
a subclass of {stream.Duplex}, unless the user specifies a socket
type other than {net.Socket}.
After this event is emitted, the request's socket will not have a `'data'`
event listener, meaning it will need to be bound in order to handle data
sent to the server on that socket.
2010-10-28 14:18:16 +02:00
### Event: `'connection'`
<!-- YAML
added: v0.1.0
-->
* `socket` {stream.Duplex}
2011-01-21 02:54:59 +01:00
This event is emitted when a new TCP stream is established. `socket` is
typically an object of type [`net.Socket`][]. Usually users will not want to
access this event. In particular, the socket will not emit `'readable'` events
because of how the protocol parser attaches to the socket. The `socket` can
also be accessed at `request.connection`.
This event can also be explicitly emitted by users to inject connections
into the HTTP server. In that case, any [`Duplex`][] stream can be passed.
2010-10-28 14:18:16 +02:00
If `socket.setTimeout()` is called here, the timeout will be replaced with
`server.keepAliveTimeout` when the socket has served a request (if
`server.keepAliveTimeout` is non-zero).
This event is guaranteed to be passed an instance of the {net.Socket} class,
a subclass of {stream.Duplex}, unless the user specifies a socket
type other than {net.Socket}.
### Event: `'request'`
<!-- YAML
added: v0.1.0
-->
2011-01-21 02:54:59 +01:00
* `request` {http.IncomingMessage}
* `response` {http.ServerResponse}
2010-10-28 14:18:16 +02:00
Emitted each time there is a request. There may be multiple requests
per connection (in the case of HTTP Keep-Alive connections).
2010-10-28 14:18:16 +02:00
### Event: `'upgrade'`
<!-- YAML
added: v0.1.94
changes:
2018-04-24, Version 10.0.0 (Current) * Assert * Calling `assert.fail()` with more than one argument is deprecated. #70dcacd710 * Calling `assert.ok()` with no arguments will now throw. #3cd7977a42 * Calling `assert.ifError()` will now throw with any argument other than `undefined` or `null`. Previously the method would throw with any truthy value. #e65a6e81ef * The `assert.rejects()` and `assert.doesNotReject()` methods have been added for working with async functions. #599337f43e * Async_hooks * Older experimental async_hooks APIs have been removed. #1cc6b993b9 * Buffer * Uses of `new Buffer()` and `Buffer()` outside of the `node_modules` directory will now emit a runtime deprecation warning. #9d4ab90117 * `Buffer.isEncoding()` now returns `undefined` for falsy values, including an empty string. #452eed956e * `Buffer.fill()` will throw if an attempt is made to fill with an empty `Buffer`. #1e802539b2 * Child Process * Undefined properties of env are ignored. #38ee25e2e2, #85739b6c5b * Console * The `console.table()` method has been added. #97ace04492 * Crypto * The `crypto.createCipher()` and `crypto.createDecipher()` methods have been deprecated. Please use `crypto.createCipheriv()` and `crypto.createDecipheriv()` instead. #81f88e30dd * The `decipher.finaltol()` method has been deprecated. #19f3927d92 * The `crypto.DEFAULT_ENCODING` property has been deprecated. #6035beea93 * The `ECDH.convertKey()` method has been added. #f2e02883e7 * The `crypto.fips` property has been deprecated. #6e7992e8b8 * Dependencies * V8 has been updated to 6.6. #9daebb48d6 * OpenSSL has been updated to 1.1.0h. #66cb29e646 * EventEmitter * The `EventEmitter.prototype.off()` method has been added as an alias for `EventEmitter.prototype.removeListener()`. #3bb6f07d52 * File System * The `fs.promises` API provides experimental promisified versions of the `fs` functions. #329fc78e49 * Invalid path errors are now thrown synchronously. #d8f73385e2 * The `fs.readFile()` method now partitions reads to avoid thread pool exhaustion. #67a4ce1c6e * HTTP * Processing of HTTP Status codes `100`, `102-199` has been improved. #baf8495078 * Multi-byte characters in URL paths are now forbidden. #b961d9fd83 * N-API * The n-api is no longer experimental. #cd7d7b15c1 * Net * The `'close'` event will be emitted after `'end'`. #9b7a6914a7 * Perf_hooks * The `PerformanceObserver` class is now an `AsyncResource` and can be monitored using `async_hooks`. #009e41826f * Trace events are now emitted for performance events. #9e509b622b * The `performance` API has been simplified. #2ec6995555 * Performance milestone marks will be emitted as trace events. #96cb4fb795 * Process * Using non-string values for `process.env` is deprecated. #5826fe4e79 * The `process.assert()` method is deprecated. #703e37cf3f * REPL * REPL now experimentally supports top-level await when using the `--experimental-repl-await` flag. #eeab7bc068 * The previously deprecated "magic mode" has been removed. #4893f70d12 * The previously deprecated `NODE_REPL_HISTORY_FILE` environment variable has been removed. #60c9ad7979 * Proxy objects are shown as Proxy objects when inspected. #90a43906ab * Streams * The `'readable'` event is now always deferred with nextTick. #1e0f3315c7 * A new `pipeline()` method has been provided for building end-to-data stream pipelines. #a5cf3feaf1 * Experimental support for async for-await has been added to `stream.Readable`. #61b4d60c5d * Timers * The `enroll()` and `unenroll()` methods have been deprecated. #68783ae0b8 * TLS * The `tls.convertNONProtocols()` method has been deprecated. #9204a0db6e * Support for NPN (next protocol negotiation) has been dropped. #5bfbe5ceae * The `ecdhCurve` default is now `'auto'`. #af78840b19 * Trace Events * A new `trace_events` top-level module allows trace event categories to be enabled/disabld at runtime. #da5d818a54 * URL * The WHATWG URL API is now a global. #312414662b * Util * `util.types.is[…]` type checks have been added. #b20af8088a * Support for bigint formatting has been added to `util.inspect()`. #39dc947409
2018-03-02 18:53:46 +01:00
- version: v10.0.0
pr-url: v10.0.0
description: Not listening to this event no longer causes the socket
to be destroyed if a client sends an Upgrade header.
-->
2010-10-28 14:18:16 +02:00
* `request` {http.IncomingMessage} Arguments for the HTTP request, as it is in
the [`'request'`][] event
* `socket` {stream.Duplex} Network socket between the server and client
* `head` {Buffer} The first packet of the upgraded stream (may be empty)
2010-10-28 14:18:16 +02:00
Emitted each time a client requests an HTTP upgrade. Listening to this event
is optional and clients cannot insist on a protocol change.
After this event is emitted, the request's socket will not have a `'data'`
event listener, meaning it will need to be bound in order to handle data
sent to the server on that socket.
2011-01-21 02:54:59 +01:00
This event is guaranteed to be passed an instance of the {net.Socket} class,
a subclass of {stream.Duplex}, unless the user specifies a socket
type other than {net.Socket}.
### `server.close([callback])`
<!-- YAML
added: v0.1.90
-->
2011-01-21 02:54:59 +01:00
* `callback` {Function}
Stops the server from accepting new connections. See [`net.Server.close()`][].
2011-01-21 02:54:59 +01:00
### `server.headersTimeout`
<!-- YAML
added: v11.3.0
-->
* {number} **Default:** `60000`
Limit the amount of time the parser will wait to receive the complete HTTP
headers.
In case of inactivity, the rules defined in [`server.timeout`][] apply. However,
that inactivity based timeout would still allow the connection to be kept open
if the headers are being sent very slowly (by default, up to a byte per 2
minutes). In order to prevent this, whenever header data arrives an additional
check is made that more than `server.headersTimeout` milliseconds has not
passed since the connection was established. If the check fails, a `'timeout'`
event is emitted on the server object, and (by default) the socket is destroyed.
See [`server.timeout`][] for more information on how timeout behavior can be
customized.
### `server.listen()`
Starts the HTTP server listening for connections.
This method is identical to [`server.listen()`][] from [`net.Server`][].
### `server.listening`
<!-- YAML
added: v5.7.0
-->
* {boolean} Indicates whether or not the server is listening for connections.
### `server.maxHeadersCount`
<!-- YAML
added: v0.7.0
-->
2011-07-26 00:13:24 +02:00
* {number} **Default:** `2000`
Limits maximum incoming headers count. If set to 0, no limit will be applied.
### `server.setTimeout([msecs][, callback])`
<!-- YAML
added: v0.9.12
changes:
2019-10-22, Version 13.0.0 (Current) Notable changes: * assert: * If the validation function passed to `assert.throws()` or `assert.rejects()` returns a value other than `true`, an assertion error will be thrown instead of the original error to highlight the programming mistake (Ruben Bridgewater). https://github.com/nodejs/node/pull/28263 * If a constructor function is passed to validate the instance of errors thrown in `assert.throws()` or `assert.reject()`, an assertion error will be thrown instead of the original error (Ruben Bridgewater). https://github.com/nodejs/node/pull/28263 * build: * Node.js releases are now built with default full-icu support. This means that all locales supported by ICU are now included and Intl-related APIs may return different values than before (Richard Lau). https://github.com/nodejs/node/pull/29887 * The minimum Xcode version supported for macOS was increased to 10. It is still possible to build Node.js with Xcode 8 but this may no longer be the case in a future v13.x release (Michael Dawson). https://github.com/nodejs/node/pull/29622 * child_process: * `ChildProcess._channel` (DEP0129) is now a Runtime deprecation (cjihrig). https://github.com/nodejs/node/pull/27949 * console: * The output `console.timeEnd()` and `console.timeLog()` will now automatically select a suitable time unit instead of always using milliseconds (Xavier Stouder). https://github.com/nodejs/node/pull/29251 * deps: * The V8 engine was updated to version 7.8. This includes performance improvements to object destructuring, memory usage and WebAssembly startup time (Myles Borins). https://github.com/nodejs/node/pull/29694) * domain: * The domain's error handler is now executed with the active domain set to the domain's parent to prevent inner recursion (Julien Gilli). https://github.com/nodejs/node/pull/26211 * fs: * The undocumented method `FSWatcher.prototype.start()` was removed (Lucas Holmquist). https://github.com/nodejs/node/pull/29905 * Calling the `open()` method on a `ReadStream` or `WriteStream` now emits a runtime deprecation warning. The methods are supposed to be internal and should not be called by user code (Robert Nagy). https://github.com/nodejs/node/pull/29061 * `fs.read/write`, `fs.readSync/writeSync` and `fd.read/write` now accept any safe integer as their `offset` parameter. The value of `offset` is also no longer coerced, so a valid type must be passed to the functions (Zach Bjornson). https://github.com/nodejs/node/pull/26572 * http: * Aborted requests no longer emit the `end` or `error` events after `aborted` (Robert Nagy). https://github.com/nodejs/node/pull/27984 https://github.com/nodejs/node/pull/20077 * Data will no longer be emitted after a socket error (Robert Nagy). https://github.com/nodejs/node/pull/28711 * The legacy HTTP parser (previously available under the `--http-parser=legacy` flag) was removed (Anna Henningsen). https://github.com/nodejs/node/pull/29589 * The `host` option for HTTP requests is now validated to be a string value (Giorgos Ntemiris). https://github.com/nodejs/node/pull/29568 * The `request.connection` and `response.connection` properties are now runtime deprecated. The equivalent `request.socket` and `response.socket` should be used instead (Robert Nagy). https://github.com/nodejs/node/pull/29015 * http, http2: * The default server timeout was removed (Ali Ijaz Sheikh). https://github.com/nodejs/node/pull/27558 * Brought 425 status code name into accordance with RFC 8470. The name changed from "Unordered Collection" to "Too Early" (Sergei Osipov). https://github.com/nodejs/node/pull/29880 * lib: * The `error.errno` property will now always be a number. To get the string value, use `error.code` instead (Joyee Cheung). https://github.com/nodejs/node/pull/28140 * module: * `module.createRequireFromPath()` is deprecated. Use `module.createRequire()` instead (cjihrig). https://github.com/nodejs/node/pull/27951 * src: * Changing the value of `process.env.TZ` will now clear the tz cache. This affects the default time zone used by methods such as `Date.prototype.toString` (Ben Noordhuis). https://github.com/nodejs/node/pull/20026 * stream: * The timing and behavior of streams was consolidated for a number of edge cases. Please look at the individual commits below for more information. PR-URL: https://github.com/nodejs/node/pull/29504
2019-09-09 14:32:18 +02:00
- version: v13.0.0
pr-url: https://github.com/nodejs/node/pull/27558
description: The default timeout changed from 120s to 0 (no timeout).
-->
* `msecs` {number} **Default:** 0 (no timeout)
* `callback` {Function}
* Returns: {http.Server}
2011-07-26 00:13:24 +02:00
Sets the timeout value for sockets, and emits a `'timeout'` event on
the Server object, passing the socket as an argument, if a timeout
occurs.
2011-07-26 00:13:24 +02:00
If there is a `'timeout'` event listener on the Server object, then it
will be called with the timed-out socket as an argument.
By default, the Server does not timeout sockets. However, if a callback
is assigned to the Server's `'timeout'` event, timeouts must be handled
explicitly.
### `server.timeout`
<!-- YAML
added: v0.9.12
changes:
2019-10-22, Version 13.0.0 (Current) Notable changes: * assert: * If the validation function passed to `assert.throws()` or `assert.rejects()` returns a value other than `true`, an assertion error will be thrown instead of the original error to highlight the programming mistake (Ruben Bridgewater). https://github.com/nodejs/node/pull/28263 * If a constructor function is passed to validate the instance of errors thrown in `assert.throws()` or `assert.reject()`, an assertion error will be thrown instead of the original error (Ruben Bridgewater). https://github.com/nodejs/node/pull/28263 * build: * Node.js releases are now built with default full-icu support. This means that all locales supported by ICU are now included and Intl-related APIs may return different values than before (Richard Lau). https://github.com/nodejs/node/pull/29887 * The minimum Xcode version supported for macOS was increased to 10. It is still possible to build Node.js with Xcode 8 but this may no longer be the case in a future v13.x release (Michael Dawson). https://github.com/nodejs/node/pull/29622 * child_process: * `ChildProcess._channel` (DEP0129) is now a Runtime deprecation (cjihrig). https://github.com/nodejs/node/pull/27949 * console: * The output `console.timeEnd()` and `console.timeLog()` will now automatically select a suitable time unit instead of always using milliseconds (Xavier Stouder). https://github.com/nodejs/node/pull/29251 * deps: * The V8 engine was updated to version 7.8. This includes performance improvements to object destructuring, memory usage and WebAssembly startup time (Myles Borins). https://github.com/nodejs/node/pull/29694) * domain: * The domain's error handler is now executed with the active domain set to the domain's parent to prevent inner recursion (Julien Gilli). https://github.com/nodejs/node/pull/26211 * fs: * The undocumented method `FSWatcher.prototype.start()` was removed (Lucas Holmquist). https://github.com/nodejs/node/pull/29905 * Calling the `open()` method on a `ReadStream` or `WriteStream` now emits a runtime deprecation warning. The methods are supposed to be internal and should not be called by user code (Robert Nagy). https://github.com/nodejs/node/pull/29061 * `fs.read/write`, `fs.readSync/writeSync` and `fd.read/write` now accept any safe integer as their `offset` parameter. The value of `offset` is also no longer coerced, so a valid type must be passed to the functions (Zach Bjornson). https://github.com/nodejs/node/pull/26572 * http: * Aborted requests no longer emit the `end` or `error` events after `aborted` (Robert Nagy). https://github.com/nodejs/node/pull/27984 https://github.com/nodejs/node/pull/20077 * Data will no longer be emitted after a socket error (Robert Nagy). https://github.com/nodejs/node/pull/28711 * The legacy HTTP parser (previously available under the `--http-parser=legacy` flag) was removed (Anna Henningsen). https://github.com/nodejs/node/pull/29589 * The `host` option for HTTP requests is now validated to be a string value (Giorgos Ntemiris). https://github.com/nodejs/node/pull/29568 * The `request.connection` and `response.connection` properties are now runtime deprecated. The equivalent `request.socket` and `response.socket` should be used instead (Robert Nagy). https://github.com/nodejs/node/pull/29015 * http, http2: * The default server timeout was removed (Ali Ijaz Sheikh). https://github.com/nodejs/node/pull/27558 * Brought 425 status code name into accordance with RFC 8470. The name changed from "Unordered Collection" to "Too Early" (Sergei Osipov). https://github.com/nodejs/node/pull/29880 * lib: * The `error.errno` property will now always be a number. To get the string value, use `error.code` instead (Joyee Cheung). https://github.com/nodejs/node/pull/28140 * module: * `module.createRequireFromPath()` is deprecated. Use `module.createRequire()` instead (cjihrig). https://github.com/nodejs/node/pull/27951 * src: * Changing the value of `process.env.TZ` will now clear the tz cache. This affects the default time zone used by methods such as `Date.prototype.toString` (Ben Noordhuis). https://github.com/nodejs/node/pull/20026 * stream: * The timing and behavior of streams was consolidated for a number of edge cases. Please look at the individual commits below for more information. PR-URL: https://github.com/nodejs/node/pull/29504
2019-09-09 14:32:18 +02:00
- version: v13.0.0
pr-url: https://github.com/nodejs/node/pull/27558
description: The default timeout changed from 120s to 0 (no timeout).
-->
2011-07-26 00:13:24 +02:00
* {number} Timeout in milliseconds. **Default:** 0 (no timeout)
2011-07-26 00:13:24 +02:00
The number of milliseconds of inactivity before a socket is presumed
to have timed out.
A value of `0` will disable the timeout behavior on incoming connections.
The socket timeout logic is set up on connection, so changing this
value only affects new connections to the server, not any existing connections.
### `server.keepAliveTimeout`
<!-- YAML
2017-05-30, Version 8.0.0 (Current) * **Async Hooks** * The `async_hooks` module has landed in core [[`4a7233c178`](https://github.com/nodejs/node/commit/4a7233c178)] [#12892](https://github.com/nodejs/node/pull/12892). * **Buffer** * Using the `--pending-deprecation` flag will cause Node.js to emit a deprecation warning when using `new Buffer(num)` or `Buffer(num)`. [[`d2d32ea5a2`](https://github.com/nodejs/node/commit/d2d32ea5a2)] [#11968](https://github.com/nodejs/node/pull/11968). * `new Buffer(num)` and `Buffer(num)` will zero-fill new `Buffer` instances [[`7eb1b4658e`](https://github.com/nodejs/node/commit/7eb1b4658e)] [#12141](https://github.com/nodejs/node/pull/12141). * Many `Buffer` methods now accept `Uint8Array` as input [[`beca3244e2`](https://github.com/nodejs/node/commit/beca3244e2)] [#10236](https://github.com/nodejs/node/pull/10236). * **Child Process** * Argument and kill signal validations have been improved [[`97a77288ce`](https://github.com/nodejs/node/commit/97a77288ce)] [#12348](https://github.com/nodejs/node/pull/12348), [[`d75fdd96aa`](https://github.com/nodejs/node/commit/d75fdd96aa)] [#10423](https://github.com/nodejs/node/pull/10423). * Child Process methods accept `Uint8Array` as input [[`627ecee9ed`](https://github.com/nodejs/node/commit/627ecee9ed)] [#10653](https://github.com/nodejs/node/pull/10653). * **Console** * Error events emitted when using `console` methods are now supressed. [[`f18e08d820`](https://github.com/nodejs/node/commit/f18e08d820)] [#9744](https://github.com/nodejs/node/pull/9744). * **Dependencies** * The npm client has been updated to 5.0.0 [[`3c3b36af0f`](https://github.com/nodejs/node/commit/3c3b36af0f)] [#12936](https://github.com/nodejs/node/pull/12936). * V8 has been updated to 5.8 with forward ABI stability to 6.0 [[`60d1aac8d2`](https://github.com/nodejs/node/commit/60d1aac8d2)] [#12784](https://github.com/nodejs/node/pull/12784). * **Domains** * Native `Promise` instances are now `Domain` aware [[`84dabe8373`](https://github.com/nodejs/node/commit/84dabe8373)] [#12489](https://github.com/nodejs/node/pull/12489). * **Errors** * We have started assigning static error codes to errors generated by Node.js. This has been done through multiple commits and is still a work in progress. * **File System** * The utility class `fs.SyncWriteStream` has been deprecated [[`7a55e34ef4`](https://github.com/nodejs/node/commit/7a55e34ef4)] [#10467](https://github.com/nodejs/node/pull/10467). * The deprecated `fs.read()` string interface has been removed [[`3c2a9361ff`](https://github.com/nodejs/node/commit/3c2a9361ff)] [#9683](https://github.com/nodejs/node/pull/9683). * **HTTP** * Improved support for userland implemented Agents [[`90403dd1d0`](https://github.com/nodejs/node/commit/90403dd1d0)] [#11567](https://github.com/nodejs/node/pull/11567). * Outgoing Cookie headers are concatenated into a single string [[`d3480776c7`](https://github.com/nodejs/node/commit/d3480776c7)] [#11259](https://github.com/nodejs/node/pull/11259). * The `httpResponse.writeHeader()` method has been deprecated [[`fb71ba4921`](https://github.com/nodejs/node/commit/fb71ba4921)] [#11355](https://github.com/nodejs/node/pull/11355). * New methods for accessing HTTP headers have been added to `OutgoingMessage` [[`3e6f1032a4`](https://github.com/nodejs/node/commit/3e6f1032a4)] [#10805](https://github.com/nodejs/node/pull/10805). * **Lib** * All deprecation messages have been assigned static identifiers [[`5de3cf099c`](https://github.com/nodejs/node/commit/5de3cf099c)] [#10116](https://github.com/nodejs/node/pull/10116). * The legacy `linkedlist` module has been removed [[`84a23391f6`](https://github.com/nodejs/node/commit/84a23391f6)] [#12113](https://github.com/nodejs/node/pull/12113). * **N-API** * Experimental support for the new N-API API has been added [[`56e881d0b0`](https://github.com/nodejs/node/commit/56e881d0b0)] [#11975](https://github.com/nodejs/node/pull/11975). * **Process** * Process warning output can be redirected to a file using the `--redirect-warnings` command-line argument [[`03e89b3ff2`](https://github.com/nodejs/node/commit/03e89b3ff2)] [#10116](https://github.com/nodejs/node/pull/10116). * Process warnings may now include additional detail [[`dd20e68b0f`](https://github.com/nodejs/node/commit/dd20e68b0f)] [#12725](https://github.com/nodejs/node/pull/12725). * **REPL** * REPL magic mode has been deprecated [[`3f27f02da0`](https://github.com/nodejs/node/commit/3f27f02da0)] [#11599](https://github.com/nodejs/node/pull/11599). * **Src** * `NODE_MODULE_VERSION` has been updated to 57 (https://github.com/nodejs/node/commit/ec7cbaf266)] [#12995](https://github.com/nodejs/node/pull/12995). * Add `--pending-deprecation` command-line argument and `NODE_PENDING_DEPRECATION` environment variable [[`a16b570f8c`](https://github.com/nodejs/node/commit/a16b570f8c)] [#11968](https://github.com/nodejs/node/pull/11968). * The `--debug` command-line argument has been deprecated. Note that using `--debug` will enable the *new* Inspector-based debug protocol as the legacy Debugger protocol previously used by Node.js has been removed. [[`010f864426`](https://github.com/nodejs/node/commit/010f864426)] [#12949](https://github.com/nodejs/node/pull/12949). * Throw when the `-c` and `-e` command-line arguments are used at the same time [[`a5f91ab230`](https://github.com/nodejs/node/commit/a5f91ab230)] [#11689](https://github.com/nodejs/node/pull/11689). * Throw when the `--use-bundled-ca` and `--use-openssl-ca` command-line arguments are used at the same time. [[`8a7db9d4b5`](https://github.com/nodejs/node/commit/8a7db9d4b5)] [#12087](https://github.com/nodejs/node/pull/12087). * **Stream** * `Stream` now supports `destroy()` and `_destroy()` APIs [[`b6e1d22fa6`](https://github.com/nodejs/node/commit/b6e1d22fa6)] [#12925](https://github.com/nodejs/node/pull/12925). * `Stream` now supports the `_final()` API [[`07c7f198db`](https://github.com/nodejs/node/commit/07c7f198db)] [#12828](https://github.com/nodejs/node/pull/12828). * **TLS** * The `rejectUnauthorized` option now defaults to `true` [[`348cc80a3c`](https://github.com/nodejs/node/commit/348cc80a3c)] [#5923](https://github.com/nodejs/node/pull/5923). * The `tls.createSecurePair()` API now emits a runtime deprecation [[`a2ae08999b`](https://github.com/nodejs/node/commit/a2ae08999b)] [#11349](https://github.com/nodejs/node/pull/11349). * A runtime deprecation will now be emitted when `dhparam` is less than 2048 bits [[`d523eb9c40`](https://github.com/nodejs/node/commit/d523eb9c40)] [#11447](https://github.com/nodejs/node/pull/11447). * **URL** * The WHATWG URL implementation is now a fully-supported Node.js API [[`d080ead0f9`](https://github.com/nodejs/node/commit/d080ead0f9)] [#12710](https://github.com/nodejs/node/pull/12710). * **Util** * `Symbol` keys are now displayed by default when using `util.inspect()` [[`5bfd13b81e`](https://github.com/nodejs/node/commit/5bfd13b81e)] [#9726](https://github.com/nodejs/node/pull/9726). * `toJSON` errors will be thrown when formatting `%j` [[`455e6f1dd8`](https://github.com/nodejs/node/commit/455e6f1dd8)] [#11708](https://github.com/nodejs/node/pull/11708). * Convert `inspect.styles` and `inspect.colors` to prototype-less objects [[`aab0d202f8`](https://github.com/nodejs/node/commit/aab0d202f8)] [#11624](https://github.com/nodejs/node/pull/11624). * The new `util.promisify()` API has been added [[`99da8e8e02`](https://github.com/nodejs/node/commit/99da8e8e02)] [#12442](https://github.com/nodejs/node/pull/12442). * **Zlib** * Support `Uint8Array` in Zlib convenience methods [[`91383e47fd`](https://github.com/nodejs/node/commit/91383e47fd)] [#12001](https://github.com/nodejs/node/pull/12001). * Zlib errors now use `RangeError` and `TypeError` consistently [[`b514bd231e`](https://github.com/nodejs/node/commit/b514bd231e)] [#11391](https://github.com/nodejs/node/pull/11391).
2017-03-16 04:26:14 +01:00
added: v8.0.0
-->
* {number} Timeout in milliseconds. **Default:** `5000` (5 seconds).
The number of milliseconds of inactivity a server needs to wait for additional
incoming data, after it has finished writing the last response, before a socket
will be destroyed. If the server receives new data before the keep-alive
timeout has fired, it will reset the regular inactivity timeout, i.e.,
[`server.timeout`][].
A value of `0` will disable the keep-alive timeout behavior on incoming
connections.
A value of `0` makes the http server behave similarly to Node.js versions prior
to 8.0.0, which did not have a keep-alive timeout.
The socket timeout logic is set up on connection, so changing this value only
affects new connections to the server, not any existing connections.
## Class: `http.ServerResponse`
<!-- YAML
added: v0.1.17
-->
* Extends: {Stream}
This object is created internally by an HTTP server, not by the user. It is
passed as the second parameter to the [`'request'`][] event.
### Event: `'close'`
<!-- YAML
added: v0.6.7
-->
2012-02-27 20:09:33 +01:00
Indicates that the underlying connection was terminated.
2011-07-26 00:13:24 +02:00
### Event: `'finish'`
<!-- YAML
added: v0.3.6
-->
2011-07-26 00:13:24 +02:00
Emitted when the response has been sent. More specifically, this event is
emitted when the last segment of the response headers and body have been
handed off to the operating system for transmission over the network. It
does not imply that the client has received anything yet.
2011-07-26 00:13:24 +02:00
### `response.addTrailers(headers)`
<!-- YAML
added: v0.3.0
-->
2011-07-26 00:13:24 +02:00
* `headers` {Object}
This method adds HTTP trailing headers (a header but at the end of the
message) to the response.
2011-07-26 00:13:24 +02:00
Trailers will **only** be emitted if chunked encoding is used for the
response; if it is not (e.g. if the request was HTTP/1.0), they will
be silently discarded.
2011-07-26 00:13:24 +02:00
HTTP requires the `Trailer` header to be sent in order to
emit trailers, with a list of the header fields in its value. E.g.,
2011-07-26 00:13:24 +02:00
```js
response.writeHead(200, { 'Content-Type': 'text/plain',
'Trailer': 'Content-MD5' });
response.write(fileData);
response.addTrailers({ 'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667' });
response.end();
```
2011-07-26 00:13:24 +02:00
Attempting to set a header field name or value that contains invalid characters
will result in a [`TypeError`][] being thrown.
2010-10-28 14:18:16 +02:00
### `response.connection`
<!-- YAML
added: v0.3.0
2019-10-22, Version 13.0.0 (Current) Notable changes: * assert: * If the validation function passed to `assert.throws()` or `assert.rejects()` returns a value other than `true`, an assertion error will be thrown instead of the original error to highlight the programming mistake (Ruben Bridgewater). https://github.com/nodejs/node/pull/28263 * If a constructor function is passed to validate the instance of errors thrown in `assert.throws()` or `assert.reject()`, an assertion error will be thrown instead of the original error (Ruben Bridgewater). https://github.com/nodejs/node/pull/28263 * build: * Node.js releases are now built with default full-icu support. This means that all locales supported by ICU are now included and Intl-related APIs may return different values than before (Richard Lau). https://github.com/nodejs/node/pull/29887 * The minimum Xcode version supported for macOS was increased to 10. It is still possible to build Node.js with Xcode 8 but this may no longer be the case in a future v13.x release (Michael Dawson). https://github.com/nodejs/node/pull/29622 * child_process: * `ChildProcess._channel` (DEP0129) is now a Runtime deprecation (cjihrig). https://github.com/nodejs/node/pull/27949 * console: * The output `console.timeEnd()` and `console.timeLog()` will now automatically select a suitable time unit instead of always using milliseconds (Xavier Stouder). https://github.com/nodejs/node/pull/29251 * deps: * The V8 engine was updated to version 7.8. This includes performance improvements to object destructuring, memory usage and WebAssembly startup time (Myles Borins). https://github.com/nodejs/node/pull/29694) * domain: * The domain's error handler is now executed with the active domain set to the domain's parent to prevent inner recursion (Julien Gilli). https://github.com/nodejs/node/pull/26211 * fs: * The undocumented method `FSWatcher.prototype.start()` was removed (Lucas Holmquist). https://github.com/nodejs/node/pull/29905 * Calling the `open()` method on a `ReadStream` or `WriteStream` now emits a runtime deprecation warning. The methods are supposed to be internal and should not be called by user code (Robert Nagy). https://github.com/nodejs/node/pull/29061 * `fs.read/write`, `fs.readSync/writeSync` and `fd.read/write` now accept any safe integer as their `offset` parameter. The value of `offset` is also no longer coerced, so a valid type must be passed to the functions (Zach Bjornson). https://github.com/nodejs/node/pull/26572 * http: * Aborted requests no longer emit the `end` or `error` events after `aborted` (Robert Nagy). https://github.com/nodejs/node/pull/27984 https://github.com/nodejs/node/pull/20077 * Data will no longer be emitted after a socket error (Robert Nagy). https://github.com/nodejs/node/pull/28711 * The legacy HTTP parser (previously available under the `--http-parser=legacy` flag) was removed (Anna Henningsen). https://github.com/nodejs/node/pull/29589 * The `host` option for HTTP requests is now validated to be a string value (Giorgos Ntemiris). https://github.com/nodejs/node/pull/29568 * The `request.connection` and `response.connection` properties are now runtime deprecated. The equivalent `request.socket` and `response.socket` should be used instead (Robert Nagy). https://github.com/nodejs/node/pull/29015 * http, http2: * The default server timeout was removed (Ali Ijaz Sheikh). https://github.com/nodejs/node/pull/27558 * Brought 425 status code name into accordance with RFC 8470. The name changed from "Unordered Collection" to "Too Early" (Sergei Osipov). https://github.com/nodejs/node/pull/29880 * lib: * The `error.errno` property will now always be a number. To get the string value, use `error.code` instead (Joyee Cheung). https://github.com/nodejs/node/pull/28140 * module: * `module.createRequireFromPath()` is deprecated. Use `module.createRequire()` instead (cjihrig). https://github.com/nodejs/node/pull/27951 * src: * Changing the value of `process.env.TZ` will now clear the tz cache. This affects the default time zone used by methods such as `Date.prototype.toString` (Ben Noordhuis). https://github.com/nodejs/node/pull/20026 * stream: * The timing and behavior of streams was consolidated for a number of edge cases. Please look at the individual commits below for more information. PR-URL: https://github.com/nodejs/node/pull/29504
2019-09-09 14:32:18 +02:00
deprecated: v13.0.0
-->
> Stability: 0 - Deprecated. Use [`response.socket`][].
* {stream.Duplex}
See [`response.socket`][].
### `response.cork()`
<!-- YAML
added: v13.2.0
-->
See [`writable.cork()`][].
### `response.end([data[, encoding]][, callback])`
<!-- YAML
added: v0.1.90
changes:
2018-04-24, Version 10.0.0 (Current) * Assert * Calling `assert.fail()` with more than one argument is deprecated. #70dcacd710 * Calling `assert.ok()` with no arguments will now throw. #3cd7977a42 * Calling `assert.ifError()` will now throw with any argument other than `undefined` or `null`. Previously the method would throw with any truthy value. #e65a6e81ef * The `assert.rejects()` and `assert.doesNotReject()` methods have been added for working with async functions. #599337f43e * Async_hooks * Older experimental async_hooks APIs have been removed. #1cc6b993b9 * Buffer * Uses of `new Buffer()` and `Buffer()` outside of the `node_modules` directory will now emit a runtime deprecation warning. #9d4ab90117 * `Buffer.isEncoding()` now returns `undefined` for falsy values, including an empty string. #452eed956e * `Buffer.fill()` will throw if an attempt is made to fill with an empty `Buffer`. #1e802539b2 * Child Process * Undefined properties of env are ignored. #38ee25e2e2, #85739b6c5b * Console * The `console.table()` method has been added. #97ace04492 * Crypto * The `crypto.createCipher()` and `crypto.createDecipher()` methods have been deprecated. Please use `crypto.createCipheriv()` and `crypto.createDecipheriv()` instead. #81f88e30dd * The `decipher.finaltol()` method has been deprecated. #19f3927d92 * The `crypto.DEFAULT_ENCODING` property has been deprecated. #6035beea93 * The `ECDH.convertKey()` method has been added. #f2e02883e7 * The `crypto.fips` property has been deprecated. #6e7992e8b8 * Dependencies * V8 has been updated to 6.6. #9daebb48d6 * OpenSSL has been updated to 1.1.0h. #66cb29e646 * EventEmitter * The `EventEmitter.prototype.off()` method has been added as an alias for `EventEmitter.prototype.removeListener()`. #3bb6f07d52 * File System * The `fs.promises` API provides experimental promisified versions of the `fs` functions. #329fc78e49 * Invalid path errors are now thrown synchronously. #d8f73385e2 * The `fs.readFile()` method now partitions reads to avoid thread pool exhaustion. #67a4ce1c6e * HTTP * Processing of HTTP Status codes `100`, `102-199` has been improved. #baf8495078 * Multi-byte characters in URL paths are now forbidden. #b961d9fd83 * N-API * The n-api is no longer experimental. #cd7d7b15c1 * Net * The `'close'` event will be emitted after `'end'`. #9b7a6914a7 * Perf_hooks * The `PerformanceObserver` class is now an `AsyncResource` and can be monitored using `async_hooks`. #009e41826f * Trace events are now emitted for performance events. #9e509b622b * The `performance` API has been simplified. #2ec6995555 * Performance milestone marks will be emitted as trace events. #96cb4fb795 * Process * Using non-string values for `process.env` is deprecated. #5826fe4e79 * The `process.assert()` method is deprecated. #703e37cf3f * REPL * REPL now experimentally supports top-level await when using the `--experimental-repl-await` flag. #eeab7bc068 * The previously deprecated "magic mode" has been removed. #4893f70d12 * The previously deprecated `NODE_REPL_HISTORY_FILE` environment variable has been removed. #60c9ad7979 * Proxy objects are shown as Proxy objects when inspected. #90a43906ab * Streams * The `'readable'` event is now always deferred with nextTick. #1e0f3315c7 * A new `pipeline()` method has been provided for building end-to-data stream pipelines. #a5cf3feaf1 * Experimental support for async for-await has been added to `stream.Readable`. #61b4d60c5d * Timers * The `enroll()` and `unenroll()` methods have been deprecated. #68783ae0b8 * TLS * The `tls.convertNONProtocols()` method has been deprecated. #9204a0db6e * Support for NPN (next protocol negotiation) has been dropped. #5bfbe5ceae * The `ecdhCurve` default is now `'auto'`. #af78840b19 * Trace Events * A new `trace_events` top-level module allows trace event categories to be enabled/disabld at runtime. #da5d818a54 * URL * The WHATWG URL API is now a global. #312414662b * Util * `util.types.is[…]` type checks have been added. #b20af8088a * Support for bigint formatting has been added to `util.inspect()`. #39dc947409
2018-03-02 18:53:46 +01:00
- version: v10.0.0
pr-url: https://github.com/nodejs/node/pull/18780
description: This method now returns a reference to `ServerResponse`.
-->
* `data` {string|Buffer}
* `encoding` {string}
* `callback` {Function}
* Returns: {this}
This method signals to the server that all of the response headers and body
have been sent; that server should consider this message complete.
The method, `response.end()`, MUST be called on each response.
If `data` is specified, it is similar in effect to calling
[`response.write(data, encoding)`][] followed by `response.end(callback)`.
2011-07-26 00:13:24 +02:00
If `callback` is specified, it will be called when the response stream
is finished.
2011-07-26 00:13:24 +02:00
### `response.finished`
<!-- YAML
added: v0.0.2
2019-12-17, Version 13.4.0 (Current) This is a security release. For more details about the vulnerability please consult the npm blog: https://blog.npmjs.org/post/189618601100/binary-planting-with-the-npm-cli Notable Changes: * deps: * update npm to 6.13.4 https://github.com/nodejs/node/pull/30904 * update uvwasi (Anna Henningsen) https://github.com/nodejs/node/pull/30745 * upgrade to libuv 1.34.0 (Colin Ihrig) https://github.com/nodejs/node/pull/30783 * doc: * docs deprecate http finished (Robert Nagy) https://github.com/nodejs/node/pull/28679 * events: * add captureRejection option (Matteo Collina) https://github.com/nodejs/node/pull/27867 * http: * add captureRejection support (Matteo Collina) https://github.com/nodejs/node/pull/27867 * llhttp opt-in insecure HTTP header parsing (Sam Roberts) https://github.com/nodejs/node/pull/30567 * http2: * implement capture rection for 'request' and 'stream' events (Matteo Collina) https://github.com/nodejs/node/pull/27867 * net: * implement capture rejections for 'connection' event (Matteo Collina) https://github.com/nodejs/node/pull/27867 * repl: * support previews by eager evaluating input (Ruben Bridgewater) https://github.com/nodejs/node/pull/30811 * stream: * add support for captureRejection option (Matteo Collina) https://github.com/nodejs/node/pull/27867 * tls: * implement capture rejections for 'secureConnection' event (Matteo Collina) https://github.com/nodejs/node/pull/27867 * expose IETF name for current cipher suite (Sam Roberts) https://github.com/nodejs/node/pull/30637 * worker: * add argv constructor option (legendecas) https://github.com/nodejs/node/pull/30559 PR-URL: https://github.com/nodejs/node/pull/30937
2019-12-13 17:02:36 +01:00
deprecated: v13.4.0
-->
2011-07-26 00:13:24 +02:00
> Stability: 0 - Deprecated. Use [`response.writableEnded`][].
* {boolean}
The `response.finished` property will be `true` if [`response.end()`][]
has been called.
### `response.flushHeaders()`
<!-- YAML
added: v1.6.0
-->
Flushes the response headers. See also: [`request.flushHeaders()`][].
### `response.getHeader(name)`
<!-- YAML
added: v0.4.0
-->
* `name` {string}
* Returns: {any}
Reads out a header that's already been queued but not sent to the client.
The name is case-insensitive. The type of the return value depends
on the arguments provided to [`response.setHeader()`][].
```js
response.setHeader('Content-Type', 'text/html');
response.setHeader('Content-Length', Buffer.byteLength(body));
response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']);
const contentType = response.getHeader('content-type');
// contentType is 'text/html'
const contentLength = response.getHeader('Content-Length');
// contentLength is of type number
const setCookie = response.getHeader('set-cookie');
// setCookie is of type string[]
```
### `response.getHeaderNames()`
<!-- YAML
added: v7.7.0
-->
* Returns: {string[]}
Returns an array containing the unique names of the current outgoing headers.
All header names are lowercase.
```js
response.setHeader('Foo', 'bar');
response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);
const headerNames = response.getHeaderNames();
// headerNames === ['foo', 'set-cookie']
```
### `response.getHeaders()`
<!-- YAML
added: v7.7.0
-->
* Returns: {Object}
Returns a shallow copy of the current outgoing headers. Since a shallow copy
is used, array values may be mutated without additional calls to various
header-related http module methods. The keys of the returned object are the
header names and the values are the respective header values. All header names
are lowercase.
The object returned by the `response.getHeaders()` method _does not_
prototypically inherit from the JavaScript `Object`. This means that typical
`Object` methods such as `obj.toString()`, `obj.hasOwnProperty()`, and others
are not defined and *will not work*.
```js
response.setHeader('Foo', 'bar');
response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);
const headers = response.getHeaders();
// headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] }
```
### `response.hasHeader(name)`
<!-- YAML
added: v7.7.0
-->
* `name` {string}
* Returns: {boolean}
Returns `true` if the header identified by `name` is currently set in the
outgoing headers. The header name matching is case-insensitive.
```js
const hasContentType = response.hasHeader('content-type');
```
### `response.headersSent`
<!-- YAML
added: v0.9.3
-->
* {boolean}
Boolean (read-only). True if headers were sent, false otherwise.
### `response.removeHeader(name)`
<!-- YAML
added: v0.4.0
-->
* `name` {string}
Removes a header that's queued for implicit sending.
```js
response.removeHeader('Content-Encoding');
```
### `response.sendDate`
<!-- YAML
added: v0.7.5
-->
2010-10-28 14:18:16 +02:00
* {boolean}
When true, the Date header will be automatically generated and sent in
the response if it is not already present in the headers. Defaults to true.
This should only be disabled for testing; HTTP requires the Date header
in responses.
### `response.setHeader(name, value)`
<!-- YAML
added: v0.4.0
-->
2010-10-28 14:18:16 +02:00
* `name` {string}
* `value` {any}
Sets a single header value for implicit headers. If this header already exists
in the to-be-sent headers, its value will be replaced. Use an array of strings
here to send multiple headers with the same name. Non-string values will be
stored without modification. Therefore, [`response.getHeader()`][] may return
non-string values. However, the non-string values will be converted to strings
for network transmission.
```js
response.setHeader('Content-Type', 'text/html');
```
or
```js
response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']);
```
Attempting to set a header field name or value that contains invalid characters
will result in a [`TypeError`][] being thrown.
When headers have been set with [`response.setHeader()`][], they will be merged
with any headers passed to [`response.writeHead()`][], with the headers passed
to [`response.writeHead()`][] given precedence.
```js
// Returns content-type = text/plain
const server = http.createServer((req, res) => {
res.setHeader('Content-Type', 'text/html');
res.setHeader('X-Foo', 'bar');
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('ok');
});
```
If [`response.writeHead()`][] method is called and this method has not been
called, it will directly write the supplied header values onto the network
channel without caching internally, and the [`response.getHeader()`][] on the
header will not yield the expected result. If progressive population of headers
is desired with potential future retrieval and modification, use
[`response.setHeader()`][] instead of [`response.writeHead()`][].
### `response.setTimeout(msecs[, callback])`
<!-- YAML
added: v0.9.12
-->
2010-10-28 14:18:16 +02:00
* `msecs` {number}
* `callback` {Function}
* Returns: {http.ServerResponse}
Sets the Socket's timeout value to `msecs`. If a callback is
provided, then it is added as a listener on the `'timeout'` event on
the response object.
If no `'timeout'` listener is added to the request, the response, or
the server, then sockets are destroyed when they time out. If a handler is
assigned to the request, the response, or the server's `'timeout'` events,
timed out sockets must be handled explicitly.
### `response.socket`
<!-- YAML
added: v0.3.0
-->
* {stream.Duplex}
Reference to the underlying socket. Usually users will not want to access
this property. In particular, the socket will not emit `'readable'` events
because of how the protocol parser attaches to the socket. After
`response.end()`, the property is nulled. The `socket` may also be accessed
via `response.connection`.
```js
const http = require('http');
const server = http.createServer((req, res) => {
const ip = res.socket.remoteAddress;
const port = res.socket.remotePort;
res.end(`Your IP address is ${ip} and your source port is ${port}.`);
}).listen(3000);
```
This property is guaranteed to be an instance of the {net.Socket} class,
a subclass of {stream.Duplex}, unless the user specified a socket
type other than {net.Socket}.
### `response.statusCode`
<!-- YAML
added: v0.4.0
-->
* {number} **Default:** `200`
When using implicit headers (not calling [`response.writeHead()`][] explicitly),
this property controls the status code that will be sent to the client when
the headers get flushed.
```js
response.statusCode = 404;
```
After response header was sent to the client, this property indicates the
status code which was sent out.
### `response.statusMessage`
<!-- YAML
added: v0.11.8
-->
* {string}
When using implicit headers (not calling [`response.writeHead()`][] explicitly),
this property controls the status message that will be sent to the client when
the headers get flushed. If this is left as `undefined` then the standard
message for the status code will be used.
2010-10-28 14:18:16 +02:00
```js
response.statusMessage = 'Not found';
```
2010-10-28 14:18:16 +02:00
After response header was sent to the client, this property indicates the
status message which was sent out.
2010-10-28 14:18:16 +02:00
### `response.uncork()`
<!-- YAML
added: v13.2.0
-->
See [`writable.uncork()`][].
### `response.writableEnded`
<!-- YAML
2019-08-20, Version 12.9.0 (Current) Notable changes: * crypto: * Added an oaepHash option to asymmetric encryption which allows users to specify a hash function when using OAEP padding. https://github.com/nodejs/node/pull/28335 * deps: * Updated V8 to 7.6.303.29. https://github.com/nodejs/node/pull/28955 * Improves the performance of various APIs such as `JSON.parse` and methods called on frozen arrays. * Adds the Promise.allSettled method. * Improves support of `BigInt` in `Intl` methods. * For more information: https://v8.dev/blog/v8-release-76 * Updated libuv to 1.31.0. https://github.com/nodejs/node/pull/29070 * `UV_FS_O_FILEMAP` has been added for faster access to memory mapped files on Windows. * `uv_fs_mkdir()` now returns `UV_EINVAL` for invalid filenames on Windows. It previously returned `UV_ENOENT`. * The `uv_fs_statfs()` API has been added. * The `uv_os_environ()` and `uv_os_free_environ()` APIs have been added. * fs: * Added `fs.writev`, `fs.writevSync` and `filehandle.writev` (promise version) methods. They allow to write an array of `ArrayBufferView`s to a file descriptor. https://github.com/nodejs/node/pull/25925 https://github.com/nodejs/node/pull/29186 * http: * Added three properties to `OutgoingMessage.prototype`: `writableObjectMode`, `writableLength` and `writableHighWaterMark` https://github.com/nodejs/node/pull/29018 * stream: * Added an new property `readableEnded` to readable streams. Its value is set to `true` when the `'end'` event is emitted. https://github.com/nodejs/node/pull/28814 * Added an new property `writableEnded` to writable streams. Its value is set to `true` after `writable.end()` has been called. https://github.com/nodejs/node/pull/28934 PR-URL: https://github.com/nodejs/node/pull/29210
2019-08-19 21:14:22 +02:00
added: v12.9.0
-->
* {boolean}
Is `true` after [`response.end()`][] has been called. This property
does not indicate whether the data has been flushed, for this use
[`response.writableFinished`][] instead.
### `response.writableFinished`
<!-- YAML
added: v12.7.0
-->
* {boolean}
Is `true` if all data has been flushed to the underlying system, immediately
before the [`'finish'`][] event is emitted.
### `response.write(chunk[, encoding][, callback])`
<!-- YAML
added: v0.1.29
-->
2010-10-28 14:18:16 +02:00
* `chunk` {string|Buffer}
* `encoding` {string} **Default:** `'utf8'`
* `callback` {Function}
* Returns: {boolean}
If this method is called and [`response.writeHead()`][] has not been called,
it will switch to implicit header mode and flush the implicit headers.
2010-10-28 14:18:16 +02:00
This sends a chunk of the response body. This method may
be called multiple times to provide successive parts of the body.
In the `http` module, the response body is omitted when the
request is a HEAD request. Similarly, the `204` and `304` responses
_must not_ include a message body.
`chunk` can be a string or a buffer. If `chunk` is a string,
the second parameter specifies how to encode it into a byte stream.
`callback` will be called when this chunk of data is flushed.
2010-10-28 14:18:16 +02:00
This is the raw HTTP body and has nothing to do with higher-level multi-part
body encodings that may be used.
2010-10-28 14:18:16 +02:00
The first time [`response.write()`][] is called, it will send the buffered
header information and the first chunk of the body to the client. The second
time [`response.write()`][] is called, Node.js assumes data will be streamed,
and sends the new data separately. That is, the response is buffered up to the
first chunk of the body.
Returns `true` if the entire data was flushed successfully to the kernel
buffer. Returns `false` if all or part of the data was queued in user memory.
`'drain'` will be emitted when the buffer is free again.
2011-02-05 00:14:58 +01:00
### `response.writeContinue()`
<!-- YAML
added: v0.3.0
-->
2011-02-05 00:14:58 +01:00
Sends a HTTP/1.1 100 Continue message to the client, indicating that
the request body should be sent. See the [`'checkContinue'`][] event on
`Server`.
### `response.writeHead(statusCode[, statusMessage][, headers])`
<!-- YAML
added: v0.1.30
changes:
- version: v11.10.0
pr-url: https://github.com/nodejs/node/pull/25974
description: Return `this` from `writeHead()` to allow chaining with
`end()`.
- version: v5.11.0, v4.4.5
pr-url: https://github.com/nodejs/node/pull/6291
description: A `RangeError` is thrown if `statusCode` is not a number in
the range `[100, 999]`.
-->
* `statusCode` {number}
* `statusMessage` {string}
* `headers` {Object}
* Returns: {http.ServerResponse}
Sends a response header to the request. The status code is a 3-digit HTTP
status code, like `404`. The last argument, `headers`, are the response headers.
Optionally one can give a human-readable `statusMessage` as the second
argument.
Returns a reference to the `ServerResponse`, so that calls can be chained.
```js
const body = 'hello world';
response
.writeHead(200, {
'Content-Length': Buffer.byteLength(body),
'Content-Type': 'text/plain'
})
.end(body);
```
This method must only be called once on a message and it must
be called before [`response.end()`][] is called.
If [`response.write()`][] or [`response.end()`][] are called before calling
this, the implicit/mutable headers will be calculated and call this function.
2010-10-28 14:18:16 +02:00
When headers have been set with [`response.setHeader()`][], they will be merged
with any headers passed to [`response.writeHead()`][], with the headers passed
to [`response.writeHead()`][] given precedence.
If this method is called and [`response.setHeader()`][] has not been called,
it will directly write the supplied header values onto the network channel
without caching internally, and the [`response.getHeader()`][] on the header
will not yield the expected result. If progressive population of headers is
desired with potential future retrieval and modification, use
[`response.setHeader()`][] instead.
```js
// Returns content-type = text/plain
const server = http.createServer((req, res) => {
res.setHeader('Content-Type', 'text/html');
res.setHeader('X-Foo', 'bar');
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('ok');
});
```
`Content-Length` is given in bytes not characters. The above example
works because the string `'hello world'` contains only single byte characters.
If the body contains higher coded characters then `Buffer.byteLength()`
should be used to determine the number of bytes in a given encoding.
And Node.js does not check whether `Content-Length` and the length of the body
which has been transmitted are equal or not.
2010-10-28 14:18:16 +02:00
Attempting to set a header field name or value that contains invalid characters
will result in a [`TypeError`][] being thrown.
### `response.writeProcessing()`
<!-- YAML
2018-04-24, Version 10.0.0 (Current) * Assert * Calling `assert.fail()` with more than one argument is deprecated. #70dcacd710 * Calling `assert.ok()` with no arguments will now throw. #3cd7977a42 * Calling `assert.ifError()` will now throw with any argument other than `undefined` or `null`. Previously the method would throw with any truthy value. #e65a6e81ef * The `assert.rejects()` and `assert.doesNotReject()` methods have been added for working with async functions. #599337f43e * Async_hooks * Older experimental async_hooks APIs have been removed. #1cc6b993b9 * Buffer * Uses of `new Buffer()` and `Buffer()` outside of the `node_modules` directory will now emit a runtime deprecation warning. #9d4ab90117 * `Buffer.isEncoding()` now returns `undefined` for falsy values, including an empty string. #452eed956e * `Buffer.fill()` will throw if an attempt is made to fill with an empty `Buffer`. #1e802539b2 * Child Process * Undefined properties of env are ignored. #38ee25e2e2, #85739b6c5b * Console * The `console.table()` method has been added. #97ace04492 * Crypto * The `crypto.createCipher()` and `crypto.createDecipher()` methods have been deprecated. Please use `crypto.createCipheriv()` and `crypto.createDecipheriv()` instead. #81f88e30dd * The `decipher.finaltol()` method has been deprecated. #19f3927d92 * The `crypto.DEFAULT_ENCODING` property has been deprecated. #6035beea93 * The `ECDH.convertKey()` method has been added. #f2e02883e7 * The `crypto.fips` property has been deprecated. #6e7992e8b8 * Dependencies * V8 has been updated to 6.6. #9daebb48d6 * OpenSSL has been updated to 1.1.0h. #66cb29e646 * EventEmitter * The `EventEmitter.prototype.off()` method has been added as an alias for `EventEmitter.prototype.removeListener()`. #3bb6f07d52 * File System * The `fs.promises` API provides experimental promisified versions of the `fs` functions. #329fc78e49 * Invalid path errors are now thrown synchronously. #d8f73385e2 * The `fs.readFile()` method now partitions reads to avoid thread pool exhaustion. #67a4ce1c6e * HTTP * Processing of HTTP Status codes `100`, `102-199` has been improved. #baf8495078 * Multi-byte characters in URL paths are now forbidden. #b961d9fd83 * N-API * The n-api is no longer experimental. #cd7d7b15c1 * Net * The `'close'` event will be emitted after `'end'`. #9b7a6914a7 * Perf_hooks * The `PerformanceObserver` class is now an `AsyncResource` and can be monitored using `async_hooks`. #009e41826f * Trace events are now emitted for performance events. #9e509b622b * The `performance` API has been simplified. #2ec6995555 * Performance milestone marks will be emitted as trace events. #96cb4fb795 * Process * Using non-string values for `process.env` is deprecated. #5826fe4e79 * The `process.assert()` method is deprecated. #703e37cf3f * REPL * REPL now experimentally supports top-level await when using the `--experimental-repl-await` flag. #eeab7bc068 * The previously deprecated "magic mode" has been removed. #4893f70d12 * The previously deprecated `NODE_REPL_HISTORY_FILE` environment variable has been removed. #60c9ad7979 * Proxy objects are shown as Proxy objects when inspected. #90a43906ab * Streams * The `'readable'` event is now always deferred with nextTick. #1e0f3315c7 * A new `pipeline()` method has been provided for building end-to-data stream pipelines. #a5cf3feaf1 * Experimental support for async for-await has been added to `stream.Readable`. #61b4d60c5d * Timers * The `enroll()` and `unenroll()` methods have been deprecated. #68783ae0b8 * TLS * The `tls.convertNONProtocols()` method has been deprecated. #9204a0db6e * Support for NPN (next protocol negotiation) has been dropped. #5bfbe5ceae * The `ecdhCurve` default is now `'auto'`. #af78840b19 * Trace Events * A new `trace_events` top-level module allows trace event categories to be enabled/disabld at runtime. #da5d818a54 * URL * The WHATWG URL API is now a global. #312414662b * Util * `util.types.is[…]` type checks have been added. #b20af8088a * Support for bigint formatting has been added to `util.inspect()`. #39dc947409
2018-03-02 18:53:46 +01:00
added: v10.0.0
-->
Sends a HTTP/1.1 102 Processing message to the client, indicating that
the request body should be sent.
## Class: `http.IncomingMessage`
<!-- YAML
added: v0.1.17
changes:
- version: v13.1.0
pr-url: https://github.com/nodejs/node/pull/30135
description: The `readableHighWaterMark` value mirrors that of the socket.
-->
2010-10-28 14:18:16 +02:00
* Extends: {stream.Readable}
An `IncomingMessage` object is created by [`http.Server`][] or
[`http.ClientRequest`][] and passed as the first argument to the [`'request'`][]
and [`'response'`][] event respectively. It may be used to access response
status, headers and data.
### Event: `'aborted'`
<!-- YAML
added: v0.3.8
-->
Emitted when the request has been aborted.
### Event: `'close'`
<!-- YAML
added: v0.4.2
-->
Indicates that the underlying connection was closed.
### `message.aborted`
<!-- YAML
added: v10.1.0
-->
* {boolean}
The `message.aborted` property will be `true` if the request has
been aborted.
### `message.complete`
<!-- YAML
added: v0.3.0
-->
* {boolean}
The `message.complete` property will be `true` if a complete HTTP message has
been received and successfully parsed.
This property is particularly useful as a means of determining if a client or
server fully transmitted a message before a connection was terminated:
```js
const req = http.request({
host: '127.0.0.1',
port: 8080,
method: 'POST'
}, (res) => {
res.resume();
res.on('end', () => {
if (!res.complete)
console.error(
'The connection was terminated while the message was still being sent');
});
});
```
### `message.destroy([error])`
<!-- YAML
added: v0.3.0
-->
* `error` {Error}
Calls `destroy()` on the socket that received the `IncomingMessage`. If `error`
is provided, an `'error'` event is emitted on the socket and `error` is passed
as an argument to any listeners on the event.
### `message.headers`
<!-- YAML
added: v0.1.5
-->
2010-10-28 14:18:16 +02:00
* {Object}
The request/response headers object.
2010-10-28 14:18:16 +02:00
Key-value pairs of header names and values. Header names are lower-cased.
2010-10-28 14:18:16 +02:00
```js
// Prints something like:
//
// { 'user-agent': 'curl/7.22.0',
// host: '127.0.0.1:8000',
// accept: '*/*' }
console.log(request.headers);
```
2010-10-28 14:18:16 +02:00
Duplicates in raw headers are handled in the following ways, depending on the
header name:
* Duplicates of `age`, `authorization`, `content-length`, `content-type`,
`etag`, `expires`, `from`, `host`, `if-modified-since`, `if-unmodified-since`,
`last-modified`, `location`, `max-forwards`, `proxy-authorization`, `referer`,
`retry-after`, `server`, or `user-agent` are discarded.
* `set-cookie` is always an array. Duplicates are added to the array.
* For duplicate `cookie` headers, the values are joined together with '; '.
* For all other headers, the values are joined together with ', '.
### `message.httpVersion`
<!-- YAML
added: v0.1.1
-->
* {string}
In case of server request, the HTTP version sent by the client. In the case of
client response, the HTTP version of the connected-to server.
Probably either `'1.1'` or `'1.0'`.
Also `message.httpVersionMajor` is the first integer and
`message.httpVersionMinor` is the second.
### `message.method`
<!-- YAML
added: v0.1.1
-->
* {string}
**Only valid for request obtained from [`http.Server`][].**
The request method as a string. Read only. Examples: `'GET'`, `'DELETE'`.
### `message.rawHeaders`
<!-- YAML
added: v0.11.6
-->
2013-08-15 23:12:12 +02:00
* {string[]}
2013-08-15 23:12:12 +02:00
The raw request/response headers list exactly as they were received.
The keys and values are in the same list. It is *not* a
list of tuples. So, the even-numbered offsets are key values, and the
2013-08-15 23:12:12 +02:00
odd-numbered offsets are the associated values.
Header names are not lowercased, and duplicates are not merged.
```js
// Prints something like:
//
// [ 'user-agent',
// 'this is invalid because there can be only one',
// 'User-Agent',
// 'curl/7.22.0',
// 'Host',
// '127.0.0.1:8000',
// 'ACCEPT',
// '*/*' ]
console.log(request.rawHeaders);
```
2013-08-15 23:12:12 +02:00
### `message.rawTrailers`
<!-- YAML
added: v0.11.6
-->
2013-08-15 23:12:12 +02:00
* {string[]}
2013-08-15 23:12:12 +02:00
The raw request/response trailer keys and values exactly as they were
received. Only populated at the `'end'` event.
### `message.setTimeout(msecs[, callback])`
<!-- YAML
added: v0.5.9
-->
* `msecs` {number}
* `callback` {Function}
* Returns: {http.IncomingMessage}
Calls `message.connection.setTimeout(msecs, callback)`.
### `message.socket`
<!-- YAML
added: v0.3.0
-->
* {stream.Duplex}
The [`net.Socket`][] object associated with the connection.
With HTTPS support, use [`request.socket.getPeerCertificate()`][] to obtain the
client's authentication details.
This property is guaranteed to be an instance of the {net.Socket} class,
a subclass of {stream.Duplex}, unless the user specified a socket
type other than {net.Socket}.
### `message.statusCode`
<!-- YAML
added: v0.1.1
-->
* {number}
**Only valid for response obtained from [`http.ClientRequest`][].**
The 3-digit HTTP response status code. E.G. `404`.
### `message.statusMessage`
<!-- YAML
added: v0.11.10
-->
* {string}
**Only valid for response obtained from [`http.ClientRequest`][].**
The HTTP response status message (reason phrase). E.G. `OK` or `Internal Server
Error`.
### `message.trailers`
<!-- YAML
added: v0.3.0
-->
* {Object}
The request/response trailers object. Only populated at the `'end'` event.
### `message.url`
<!-- YAML
added: v0.1.90
-->
* {string}
**Only valid for request obtained from [`http.Server`][].**
Request URL string. This contains only the URL that is
present in the actual HTTP request. If the request is:
```txt
GET /status?name=ryan HTTP/1.1\r\n
Accept: text/plain\r\n
\r\n
```
To parse the URL into its parts:
```js
new URL(request.url, `http://${request.headers.host}`);
```
When `request.url` is `'/status?name=ryan'` and
`request.headers.host` is `'localhost:3000'`:
```console
$ node
> new URL(request.url, `http://${request.headers.host}`)
URL {
href: 'http://localhost:3000/status?name=ryan',
origin: 'http://localhost:3000',
protocol: 'http:',
username: '',
password: '',
host: 'localhost:3000',
hostname: 'localhost',
port: '3000',
pathname: '/status',
search: '?name=ryan',
searchParams: URLSearchParams { 'name' => 'ryan' },
hash: ''
}
```
2010-10-28 14:18:16 +02:00
## `http.METHODS`
<!-- YAML
added: v0.11.8
-->
* {string[]}
A list of the HTTP methods that are supported by the parser.
## `http.STATUS_CODES`
<!-- YAML
added: v0.1.22
-->
* {Object}
A collection of all the standard HTTP response status codes, and the
short description of each. For example, `http.STATUS_CODES[404] === 'Not
Found'`.
## `http.createServer([options][, requestListener])`
<!-- YAML
added: v0.1.13
changes:
- version: v13.8.0
pr-url: https://github.com/nodejs/node/pull/31448
description: The `insecureHTTPParser` option is supported now.
- version: v13.3.0
pr-url: https://github.com/nodejs/node/pull/30570
description: The `maxHeaderSize` option is supported now.
- version: v9.6.0, v8.12.0
pr-url: https://github.com/nodejs/node/pull/15752
description: The `options` argument is supported now.
-->
* `options` {Object}
* `IncomingMessage` {http.IncomingMessage} Specifies the `IncomingMessage`
class to be used. Useful for extending the original `IncomingMessage`.
**Default:** `IncomingMessage`.
* `ServerResponse` {http.ServerResponse} Specifies the `ServerResponse` class
to be used. Useful for extending the original `ServerResponse`. **Default:**
`ServerResponse`.
* `insecureHTTPParser` {boolean} Use an insecure HTTP parser that accepts
invalid HTTP headers when `true`. Using the insecure parser should be
avoided. See [`--insecure-http-parser`][] for more information.
**Default:** `false`
* `maxHeaderSize` {number} Optionally overrides the value of
[`--max-http-header-size`][] for requests received by this server, i.e.
the maximum length of request headers in bytes.
**Default:** 16384 (16KB).
* `requestListener` {Function}
* Returns: {http.Server}
Returns a new instance of [`http.Server`][].
The `requestListener` is a function which is automatically
added to the [`'request'`][] event.
## `http.get(options[, callback])`
## `http.get(url[, options][, callback])`
<!-- YAML
added: v0.3.6
changes:
- version: v10.9.0
pr-url: https://github.com/nodejs/node/pull/21616
description: The `url` parameter can now be passed along with a separate
`options` object.
- version: v7.5.0
pr-url: https://github.com/nodejs/node/pull/10638
description: The `options` parameter can be a WHATWG `URL` object.
-->
* `url` {string | URL}
* `options` {Object} Accepts the same `options` as
[`http.request()`][], with the `method` always set to `GET`.
Properties that are inherited from the prototype are ignored.
* `callback` {Function}
* Returns: {http.ClientRequest}
Since most requests are GET requests without bodies, Node.js provides this
convenience method. The only difference between this method and
[`http.request()`][] is that it sets the method to GET and calls `req.end()`
automatically. The callback must take care to consume the response
data for reasons stated in [`http.ClientRequest`][] section.
The `callback` is invoked with a single argument that is an instance of
[`http.IncomingMessage`][].
JSON fetching example:
```js
http.get('http://nodejs.org/dist/index.json', (res) => {
const { statusCode } = res;
const contentType = res.headers['content-type'];
let error;
if (statusCode !== 200) {
error = new Error('Request Failed.\n' +
`Status Code: ${statusCode}`);
} else if (!/^application\/json/.test(contentType)) {
error = new Error('Invalid content-type.\n' +
`Expected application/json but received ${contentType}`);
}
if (error) {
console.error(error.message);
// Consume response data to free up memory
res.resume();
return;
}
res.setEncoding('utf8');
let rawData = '';
res.on('data', (chunk) => { rawData += chunk; });
res.on('end', () => {
try {
const parsedData = JSON.parse(rawData);
console.log(parsedData);
} catch (e) {
console.error(e.message);
}
});
}).on('error', (e) => {
console.error(`Got error: ${e.message}`);
});
```
## `http.globalAgent`
<!-- YAML
added: v0.5.9
-->
* {http.Agent}
Global instance of `Agent` which is used as the default for all HTTP client
requests.
## `http.maxHeaderSize`
<!-- YAML
added: v11.6.0
-->
* {number}
Read-only property specifying the maximum allowed size of HTTP headers in bytes.
Defaults to 8KB. Configurable using the [`--max-http-header-size`][] CLI option.
This can be overridden for servers and client requests by passing the
`maxHeaderSize` option.
## `http.request(options[, callback])`
## `http.request(url[, options][, callback])`
<!-- YAML
added: v0.3.6
changes:
- version: v13.8.0
pr-url: https://github.com/nodejs/node/pull/31448
description: The `insecureHTTPParser` option is supported now.
- version: v13.3.0
pr-url: https://github.com/nodejs/node/pull/30570
description: The `maxHeaderSize` option is supported now.
- version: v10.9.0
pr-url: https://github.com/nodejs/node/pull/21616
description: The `url` parameter can now be passed along with a separate
`options` object.
- version: v7.5.0
pr-url: https://github.com/nodejs/node/pull/10638
description: The `options` parameter can be a WHATWG `URL` object.
-->
* `url` {string | URL}
* `options` {Object}
* `agent` {http.Agent | boolean} Controls [`Agent`][] behavior. Possible
values:
* `undefined` (default): use [`http.globalAgent`][] for this host and port.
* `Agent` object: explicitly use the passed in `Agent`.
* `false`: causes a new `Agent` with default values to be used.
* `auth` {string} Basic authentication i.e. `'user:password'` to compute an
Authorization header.
* `createConnection` {Function} A function that produces a socket/stream to
use for the request when the `agent` option is not used. This can be used to
avoid creating a custom `Agent` class just to override the default
`createConnection` function. See [`agent.createConnection()`][] for more
details. Any [`Duplex`][] stream is a valid return value.
* `defaultPort` {number} Default port for the protocol. **Default:**
`agent.defaultPort` if an `Agent` is used, else `undefined`.
* `family` {number} IP address family to use when resolving `host` or
`hostname`. Valid values are `4` or `6`. When unspecified, both IP v4 and
v6 will be used.
* `headers` {Object} An object containing request headers.
* `host` {string} A domain name or IP address of the server to issue the
request to. **Default:** `'localhost'`.
* `hostname` {string} Alias for `host`. To support [`url.parse()`][],
`hostname` will be used if both `host` and `hostname` are specified.
* `insecureHTTPParser` {boolean} Use an insecure HTTP parser that accepts
invalid HTTP headers when `true`. Using the insecure parser should be
avoided. See [`--insecure-http-parser`][] for more information.
**Default:** `false`
* `localAddress` {string} Local interface to bind for network connections.
* `lookup` {Function} Custom lookup function. **Default:** [`dns.lookup()`][].
* `maxHeaderSize` {number} Optionally overrides the value of
[`--max-http-header-size`][] for requests received from the server, i.e.
the maximum length of response headers in bytes.
**Default:** 16384 (16KB).
* `method` {string} A string specifying the HTTP request method. **Default:**
`'GET'`.
* `path` {string} Request path. Should include query string if any.
E.G. `'/index.html?page=12'`. An exception is thrown when the request path
contains illegal characters. Currently, only spaces are rejected but that
may change in the future. **Default:** `'/'`.
* `port` {number} Port of remote server. **Default:** `defaultPort` if set,
else `80`.
* `protocol` {string} Protocol to use. **Default:** `'http:'`.
* `setHost` {boolean}: Specifies whether or not to automatically add the
`Host` header. Defaults to `true`.
* `socketPath` {string} Unix Domain Socket (cannot be used if one of `host`
or `port` is specified, those specify a TCP Socket).
* `timeout` {number}: A number specifying the socket timeout in milliseconds.
This will set the timeout before the socket is connected.
* `callback` {Function}
* Returns: {http.ClientRequest}
Node.js maintains several connections per server to make HTTP requests.
This function allows one to transparently issue requests.
`url` can be a string or a [`URL`][] object. If `url` is a
string, it is automatically parsed with [`new URL()`][]. If it is a [`URL`][]
object, it will be automatically converted to an ordinary `options` object.
If both `url` and `options` are specified, the objects are merged, with the
`options` properties taking precedence.
The optional `callback` parameter will be added as a one-time listener for
the [`'response'`][] event.
`http.request()` returns an instance of the [`http.ClientRequest`][]
class. The `ClientRequest` instance is a writable stream. If one needs to
upload a file with a POST request, then write to the `ClientRequest` object.
```js
const postData = querystring.stringify({
'msg': 'Hello World!'
});
const options = {
hostname: 'www.google.com',
port: 80,
path: '/upload',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(postData)
}
};
const req = http.request(options, (res) => {
console.log(`STATUS: ${res.statusCode}`);
console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
res.setEncoding('utf8');
res.on('data', (chunk) => {
console.log(`BODY: ${chunk}`);
});
res.on('end', () => {
console.log('No more data in response.');
});
});
req.on('error', (e) => {
console.error(`problem with request: ${e.message}`);
});
// Write data to request body
req.write(postData);
req.end();
```
In the example `req.end()` was called. With `http.request()` one
must always call `req.end()` to signify the end of the request -
even if there is no data being written to the request body.
If any error is encountered during the request (be that with DNS resolution,
TCP level errors, or actual HTTP parse errors) an `'error'` event is emitted
on the returned request object. As with all `'error'` events, if no listeners
are registered the error will be thrown.
There are a few special headers that should be noted.
* Sending a 'Connection: keep-alive' will notify Node.js that the connection to
the server should be persisted until the next request.
* Sending a 'Content-Length' header will disable the default chunked encoding.
* Sending an 'Expect' header will immediately send the request headers.
Usually, when sending 'Expect: 100-continue', both a timeout and a listener
for the `'continue'` event should be set. See RFC 2616 Section 8.2.3 for more
information.
* Sending an Authorization header will override using the `auth` option
to compute basic authentication.
Example using a [`URL`][] as `options`:
```js
const options = new URL('http://abc:xyz@example.com');
const req = http.request(options, (res) => {
// ...
});
```
In a successful request, the following events will be emitted in the following
order:
* `'socket'`
* `'response'`
* `'data'` any number of times, on the `res` object
(`'data'` will not be emitted at all if the response body is empty, for
instance, in most redirects)
* `'end'` on the `res` object
* `'close'`
In the case of a connection error, the following events will be emitted:
* `'socket'`
* `'error'`
* `'close'`
In the case of a premature connection close before the response is received,
the following events will be emitted in the following order:
* `'socket'`
* `'error'` with an error with message `'Error: socket hang up'` and code
`'ECONNRESET'`
* `'close'`
In the case of a premature connection close after the response is received,
the following events will be emitted in the following order:
* `'socket'`
* `'response'`
* `'data'` any number of times, on the `res` object
* (connection closed here)
* `'aborted'` on the `res` object
* `'close'`
* `'close'` on the `res` object
If `req.abort()` is called before the connection succeeds, the following events
will be emitted in the following order:
* `'socket'`
* (`req.abort()` called here)
* `'abort'`
* `'error'` with an error with message `'Error: socket hang up'` and code
`'ECONNRESET'`
* `'close'`
If `req.abort()` is called after the response is received, the following events
will be emitted in the following order:
* `'socket'`
* `'response'`
* `'data'` any number of times, on the `res` object
* (`req.abort()` called here)
* `'abort'`
* `'aborted'` on the `res` object
* `'close'`
* `'close'` on the `res` object
Setting the `timeout` option or using the `setTimeout()` function will
not abort the request or do anything besides add a `'timeout'` event.
[`--insecure-http-parser`]: cli.html#cli_insecure_http_parser
[`--max-http-header-size`]: cli.html#cli_max_http_header_size_size
[`'checkContinue'`]: #http_event_checkcontinue
[`'request'`]: #http_event_request
[`'response'`]: #http_event_response
[`'upgrade'`]: #http_event_upgrade
[`Agent`]: #http_class_http_agent
[`Duplex`]: stream.html#stream_class_stream_duplex
[`TypeError`]: errors.html#errors_class_typeerror
[`URL`]: url.html#url_the_whatwg_url_api
[`agent.createConnection()`]: #http_agent_createconnection_options_callback
[`agent.getName()`]: #http_agent_getname_options
[`destroy()`]: #http_agent_destroy
[`dns.lookup()`]: dns.html#dns_dns_lookup_hostname_options_callback
[`'finish'`]: #http_event_finish
[`getHeader(name)`]: #http_request_getheader_name
[`http.Agent`]: #http_class_http_agent
[`http.ClientRequest`]: #http_class_http_clientrequest
[`http.IncomingMessage`]: #http_class_http_incomingmessage
[`http.Server`]: #http_class_http_server
[`http.get()`]: #http_http_get_options_callback
[`http.globalAgent`]: #http_http_globalagent
[`http.request()`]: #http_http_request_options_callback
[`message.headers`]: #http_message_headers
[`net.Server.close()`]: net.html#net_server_close_callback
[`net.Server`]: net.html#net_class_net_server
[`net.Socket`]: net.html#net_class_net_socket
[`net.createConnection()`]: net.html#net_net_createconnection_options_connectlistener
[`new URL()`]: url.html#url_constructor_new_url_input_base
[`removeHeader(name)`]: #http_request_removeheader_name
[`request.end()`]: #http_request_end_data_encoding_callback
[`request.flushHeaders()`]: #http_request_flushheaders
[`request.getHeader()`]: #http_request_getheader_name
[`request.setHeader()`]: #http_request_setheader_name_value
[`request.setTimeout()`]: #http_request_settimeout_timeout_callback
[`request.socket.getPeerCertificate()`]: tls.html#tls_tlssocket_getpeercertificate_detailed
[`request.socket`]: #http_request_socket
[`request.writableFinished`]: #http_request_writablefinished
[`request.writableEnded`]: #http_request_writableended
[`request.write(data, encoding)`]: #http_request_write_chunk_encoding_callback
[`response.end()`]: #http_response_end_data_encoding_callback
[`response.getHeader()`]: #http_response_getheader_name
[`response.setHeader()`]: #http_response_setheader_name_value
[`response.socket`]: #http_response_socket
[`response.writableFinished`]: #http_response_writablefinished
[`response.writableEnded`]: #http_response_writableended
[`response.write()`]: #http_response_write_chunk_encoding_callback
[`response.write(data, encoding)`]: #http_response_write_chunk_encoding_callback
[`response.writeContinue()`]: #http_response_writecontinue
[`response.writeHead()`]: #http_response_writehead_statuscode_statusmessage_headers
[`server.listen()`]: net.html#net_server_listen
[`server.timeout`]: #http_server_timeout
[`setHeader(name, value)`]: #http_request_setheader_name_value
[`socket.connect()`]: net.html#net_socket_connect_options_connectlistener
[`socket.setKeepAlive()`]: net.html#net_socket_setkeepalive_enable_initialdelay
[`socket.setNoDelay()`]: net.html#net_socket_setnodelay_nodelay
[`socket.setTimeout()`]: net.html#net_socket_settimeout_timeout_callback
[`socket.unref()`]: net.html#net_socket_unref
[`url.parse()`]: url.html#url_url_parse_urlstring_parsequerystring_slashesdenotehost
[`HPE_HEADER_OVERFLOW`]: errors.html#errors_hpe_header_overflow
[`writable.cork()`]: stream.html#stream_writable_cork
[`writable.uncork()`]: stream.html#stream_writable_uncork