UNPKG

54.6 kBTypeScriptView Raw
1/**
2 * To use the HTTP server and client one must `require('http')`.
3 *
4 * The HTTP interfaces in Node.js are designed to support many features
5 * of the protocol which have been traditionally difficult to use.
6 * In particular, large, possibly chunk-encoded, messages. The interface is
7 * careful to never buffer entire requests or responses, so the
8 * user is able to stream data.
9 *
10 * HTTP message headers are represented by an object like this:
11 *
12 * ```js
13 * { 'content-length': '123',
14 * 'content-type': 'text/plain',
15 * 'connection': 'keep-alive',
16 * 'host': 'mysite.com',
17 * 'accept': '*' }
18 * ```
19 *
20 * Keys are lowercased. Values are not modified.
21 *
22 * In order to support the full spectrum of possible HTTP applications, the Node.js
23 * HTTP API is very low-level. It deals with stream handling and message
24 * parsing only. It parses a message into headers and body but it does not
25 * parse the actual headers or the body.
26 *
27 * See `message.headers` for details on how duplicate headers are handled.
28 *
29 * The raw headers as they were received are retained in the `rawHeaders`property, which is an array of `[key, value, key2, value2, ...]`. For
30 * example, the previous message header object might have a `rawHeaders`list like the following:
31 *
32 * ```js
33 * [ 'ConTent-Length', '123456',
34 * 'content-LENGTH', '123',
35 * 'content-type', 'text/plain',
36 * 'CONNECTION', 'keep-alive',
37 * 'Host', 'mysite.com',
38 * 'accepT', '*' ]
39 * ```
40 * @see [source](https://github.com/nodejs/node/blob/v16.4.2/lib/http.js)
41 */
42declare module 'http' {
43 import * as stream from 'node:stream';
44 import { URL } from 'node:url';
45 import { Socket, Server as NetServer } from 'node:net';
46 // incoming headers will never contain number
47 interface IncomingHttpHeaders extends NodeJS.Dict<string | string[]> {
48 accept?: string | undefined;
49 'accept-language'?: string | undefined;
50 'accept-patch'?: string | undefined;
51 'accept-ranges'?: string | undefined;
52 'access-control-allow-credentials'?: string | undefined;
53 'access-control-allow-headers'?: string | undefined;
54 'access-control-allow-methods'?: string | undefined;
55 'access-control-allow-origin'?: string | undefined;
56 'access-control-expose-headers'?: string | undefined;
57 'access-control-max-age'?: string | undefined;
58 'access-control-request-headers'?: string | undefined;
59 'access-control-request-method'?: string | undefined;
60 age?: string | undefined;
61 allow?: string | undefined;
62 'alt-svc'?: string | undefined;
63 authorization?: string | undefined;
64 'cache-control'?: string | undefined;
65 connection?: string | undefined;
66 'content-disposition'?: string | undefined;
67 'content-encoding'?: string | undefined;
68 'content-language'?: string | undefined;
69 'content-length'?: string | undefined;
70 'content-location'?: string | undefined;
71 'content-range'?: string | undefined;
72 'content-type'?: string | undefined;
73 cookie?: string | undefined;
74 date?: string | undefined;
75 etag?: string | undefined;
76 expect?: string | undefined;
77 expires?: string | undefined;
78 forwarded?: string | undefined;
79 from?: string | undefined;
80 host?: string | undefined;
81 'if-match'?: string | undefined;
82 'if-modified-since'?: string | undefined;
83 'if-none-match'?: string | undefined;
84 'if-unmodified-since'?: string | undefined;
85 'last-modified'?: string | undefined;
86 location?: string | undefined;
87 origin?: string | undefined;
88 pragma?: string | undefined;
89 'proxy-authenticate'?: string | undefined;
90 'proxy-authorization'?: string | undefined;
91 'public-key-pins'?: string | undefined;
92 range?: string | undefined;
93 referer?: string | undefined;
94 'retry-after'?: string | undefined;
95 'sec-websocket-accept'?: string | undefined;
96 'sec-websocket-extensions'?: string | undefined;
97 'sec-websocket-key'?: string | undefined;
98 'sec-websocket-protocol'?: string | undefined;
99 'sec-websocket-version'?: string | undefined;
100 'set-cookie'?: string[] | undefined;
101 'strict-transport-security'?: string | undefined;
102 tk?: string | undefined;
103 trailer?: string | undefined;
104 'transfer-encoding'?: string | undefined;
105 upgrade?: string | undefined;
106 'user-agent'?: string | undefined;
107 vary?: string | undefined;
108 via?: string | undefined;
109 warning?: string | undefined;
110 'www-authenticate'?: string | undefined;
111 }
112 // outgoing headers allows numbers (as they are converted internally to strings)
113 type OutgoingHttpHeader = number | string | string[];
114 interface OutgoingHttpHeaders extends NodeJS.Dict<OutgoingHttpHeader> {}
115 interface ClientRequestArgs {
116 abort?: AbortSignal | undefined;
117 protocol?: string | null | undefined;
118 host?: string | null | undefined;
119 hostname?: string | null | undefined;
120 family?: number | undefined;
121 port?: number | string | null | undefined;
122 defaultPort?: number | string | undefined;
123 localAddress?: string | undefined;
124 socketPath?: string | undefined;
125 /**
126 * @default 8192
127 */
128 maxHeaderSize?: number | undefined;
129 method?: string | undefined;
130 path?: string | null | undefined;
131 headers?: OutgoingHttpHeaders | undefined;
132 auth?: string | null | undefined;
133 agent?: Agent | boolean | undefined;
134 _defaultAgent?: Agent | undefined;
135 timeout?: number | undefined;
136 setHost?: boolean | undefined;
137 // https://github.com/nodejs/node/blob/master/lib/_http_client.js#L278
138 createConnection?: ((options: ClientRequestArgs, oncreate: (err: Error, socket: Socket) => void) => Socket) | undefined;
139 }
140 interface ServerOptions {
141 IncomingMessage?: typeof IncomingMessage | undefined;
142 ServerResponse?: typeof ServerResponse | undefined;
143 /**
144 * Optionally overrides the value of
145 * `--max-http-header-size` for requests received by this server, i.e.
146 * the maximum length of request headers in bytes.
147 * @default 8192
148 */
149 maxHeaderSize?: number | undefined;
150 /**
151 * Use an insecure HTTP parser that accepts invalid HTTP headers when true.
152 * Using the insecure parser should be avoided.
153 * See --insecure-http-parser for more information.
154 * @default false
155 */
156 insecureHTTPParser?: boolean | undefined;
157 }
158 type RequestListener = (req: IncomingMessage, res: ServerResponse) => void;
159 interface HttpBase {
160 setTimeout(msecs?: number, callback?: () => void): this;
161 setTimeout(callback: () => void): this;
162 /**
163 * Limits maximum incoming headers count. If set to 0, no limit will be applied.
164 * @default 2000
165 * {@link https://nodejs.org/api/http.html#http_server_maxheaderscount}
166 */
167 maxHeadersCount: number | null;
168 timeout: number;
169 /**
170 * Limit the amount of time the parser will wait to receive the complete HTTP headers.
171 * @default 60000
172 * {@link https://nodejs.org/api/http.html#http_server_headerstimeout}
173 */
174 headersTimeout: number;
175 keepAliveTimeout: number;
176 /**
177 * Sets the timeout value in milliseconds for receiving the entire request from the client.
178 * @default 0
179 * {@link https://nodejs.org/api/http.html#http_server_requesttimeout}
180 */
181 requestTimeout: number;
182 }
183 interface Server extends HttpBase {}
184 /**
185 * @since v0.1.17
186 */
187 class Server extends NetServer {
188 constructor(requestListener?: RequestListener);
189 constructor(options: ServerOptions, requestListener?: RequestListener);
190 }
191 /**
192 * This class serves as the parent class of {@link ClientRequest} and {@link ServerResponse}. It is an abstract of outgoing message from
193 * the perspective of the participants of HTTP transaction.
194 * @since v0.1.17
195 */
196 class OutgoingMessage extends stream.Writable {
197 readonly req: IncomingMessage;
198 chunkedEncoding: boolean;
199 shouldKeepAlive: boolean;
200 useChunkedEncodingByDefault: boolean;
201 sendDate: boolean;
202 /**
203 * @deprecated Use `writableEnded` instead.
204 */
205 finished: boolean;
206 /**
207 * Read-only. `true` if the headers were sent, otherwise `false`.
208 * @since v0.9.3
209 */
210 readonly headersSent: boolean;
211 /**
212 * Aliases of `outgoingMessage.socket`
213 * @since v0.3.0
214 * @deprecated Since v15.12.0 - Use `socket` instead.
215 */
216 readonly connection: Socket | null;
217 /**
218 * Reference to the underlying socket. Usually, users will not want to access
219 * this property.
220 *
221 * After calling `outgoingMessage.end()`, this property will be nulled.
222 * @since v0.3.0
223 */
224 readonly socket: Socket | null;
225 constructor();
226 /**
227 * occurs, Same as binding to the `timeout` event.
228 *
229 * Once a socket is associated with the message and is connected,`socket.setTimeout()` will be called with `msecs` as the first parameter.
230 * @since v0.9.12
231 * @param callback Optional function to be called when a timeout
232 */
233 setTimeout(msecs: number, callback?: () => void): this;
234 /**
235 * Sets a single header value for the header object.
236 * @since v0.4.0
237 * @param name Header name
238 * @param value Header value
239 */
240 setHeader(name: string, value: number | string | ReadonlyArray<string>): this;
241 /**
242 * Gets the value of HTTP header with the given name. If such a name doesn't
243 * exist in message, it will be `undefined`.
244 * @since v0.4.0
245 * @param name Name of header
246 */
247 getHeader(name: string): number | string | string[] | undefined;
248 /**
249 * Returns a shallow copy of the current outgoing headers. Since a shallow
250 * copy is used, array values may be mutated without additional calls to
251 * various header-related HTTP module methods. The keys of the returned
252 * object are the header names and the values are the respective header
253 * values. All header names are lowercase.
254 *
255 * The object returned by the `outgoingMessage.getHeaders()` method does
256 * not prototypically inherit from the JavaScript Object. This means that
257 * typical Object methods such as `obj.toString()`, `obj.hasOwnProperty()`,
258 * and others are not defined and will not work.
259 *
260 * ```js
261 * outgoingMessage.setHeader('Foo', 'bar');
262 * outgoingMessage.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);
263 *
264 * const headers = outgoingMessage.getHeaders();
265 * // headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] }
266 * ```
267 * @since v8.0.0
268 */
269 getHeaders(): OutgoingHttpHeaders;
270 /**
271 * Returns an array of names of headers of the outgoing outgoingMessage. All
272 * names are lowercase.
273 * @since v8.0.0
274 */
275 getHeaderNames(): string[];
276 /**
277 * Returns `true` if the header identified by `name` is currently set in the
278 * outgoing headers. The header name is case-insensitive.
279 *
280 * ```js
281 * const hasContentType = outgoingMessage.hasHeader('content-type');
282 * ```
283 * @since v8.0.0
284 */
285 hasHeader(name: string): boolean;
286 /**
287 * Removes a header that is queued for implicit sending.
288 *
289 * ```js
290 * outgoingMessage.removeHeader('Content-Encoding');
291 * ```
292 * @since v0.4.0
293 */
294 removeHeader(name: string): void;
295 /**
296 * Adds HTTP trailers (headers but at the end of the message) to the message.
297 *
298 * Trailers are **only** be emitted if the message is chunked encoded. If not,
299 * the trailer will be silently discarded.
300 *
301 * HTTP requires the `Trailer` header to be sent to emit trailers,
302 * with a list of header fields in its value, e.g.
303 *
304 * ```js
305 * message.writeHead(200, { 'Content-Type': 'text/plain',
306 * 'Trailer': 'Content-MD5' });
307 * message.write(fileData);
308 * message.addTrailers({ 'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667' });
309 * message.end();
310 * ```
311 *
312 * Attempting to set a header field name or value that contains invalid characters
313 * will result in a `TypeError` being thrown.
314 * @since v0.3.0
315 */
316 addTrailers(headers: OutgoingHttpHeaders | ReadonlyArray<[string, string]>): void;
317 /**
318 * Compulsorily flushes the message headers
319 *
320 * For efficiency reason, Node.js normally buffers the message headers
321 * until `outgoingMessage.end()` is called or the first chunk of message data
322 * is written. It then tries to pack the headers and data into a single TCP
323 * packet.
324 *
325 * It is usually desired (it saves a TCP round-trip), but not when the first
326 * data is not sent until possibly much later. `outgoingMessage.flushHeaders()`bypasses the optimization and kickstarts the request.
327 * @since v1.6.0
328 */
329 flushHeaders(): void;
330 }
331 /**
332 * This object is created internally by an HTTP server, not by the user. It is
333 * passed as the second parameter to the `'request'` event.
334 * @since v0.1.17
335 */
336 class ServerResponse extends OutgoingMessage {
337 /**
338 * When using implicit headers (not calling `response.writeHead()` explicitly),
339 * this property controls the status code that will be sent to the client when
340 * the headers get flushed.
341 *
342 * ```js
343 * response.statusCode = 404;
344 * ```
345 *
346 * After response header was sent to the client, this property indicates the
347 * status code which was sent out.
348 * @since v0.4.0
349 */
350 statusCode: number;
351 /**
352 * When using implicit headers (not calling `response.writeHead()` explicitly),
353 * this property controls the status message that will be sent to the client when
354 * the headers get flushed. If this is left as `undefined` then the standard
355 * message for the status code will be used.
356 *
357 * ```js
358 * response.statusMessage = 'Not found';
359 * ```
360 *
361 * After response header was sent to the client, this property indicates the
362 * status message which was sent out.
363 * @since v0.11.8
364 */
365 statusMessage: string;
366 constructor(req: IncomingMessage);
367 assignSocket(socket: Socket): void;
368 detachSocket(socket: Socket): void;
369 /**
370 * Sends a HTTP/1.1 100 Continue message to the client, indicating that
371 * the request body should be sent. See the `'checkContinue'` event on`Server`.
372 * @since v0.3.0
373 */
374 writeContinue(callback?: () => void): void;
375 /**
376 * Sends a response header to the request. The status code is a 3-digit HTTP
377 * status code, like `404`. The last argument, `headers`, are the response headers.
378 * Optionally one can give a human-readable `statusMessage` as the second
379 * argument.
380 *
381 * `headers` may be an `Array` where the keys and values are in the same list.
382 * It is _not_ a list of tuples. So, the even-numbered offsets are key values,
383 * and the odd-numbered offsets are the associated values. The array is in the same
384 * format as `request.rawHeaders`.
385 *
386 * Returns a reference to the `ServerResponse`, so that calls can be chained.
387 *
388 * ```js
389 * const body = 'hello world';
390 * response
391 * .writeHead(200, {
392 * 'Content-Length': Buffer.byteLength(body),
393 * 'Content-Type': 'text/plain'
394 * })
395 * .end(body);
396 * ```
397 *
398 * This method must only be called once on a message and it must
399 * be called before `response.end()` is called.
400 *
401 * If `response.write()` or `response.end()` are called before calling
402 * this, the implicit/mutable headers will be calculated and call this function.
403 *
404 * When headers have been set with `response.setHeader()`, they will be merged
405 * with any headers passed to `response.writeHead()`, with the headers passed
406 * to `response.writeHead()` given precedence.
407 *
408 * If this method is called and `response.setHeader()` has not been called,
409 * it will directly write the supplied header values onto the network channel
410 * without caching internally, and the `response.getHeader()` on the header
411 * will not yield the expected result. If progressive population of headers is
412 * desired with potential future retrieval and modification, use `response.setHeader()` instead.
413 *
414 * ```js
415 * // Returns content-type = text/plain
416 * const server = http.createServer((req, res) => {
417 * res.setHeader('Content-Type', 'text/html');
418 * res.setHeader('X-Foo', 'bar');
419 * res.writeHead(200, { 'Content-Type': 'text/plain' });
420 * res.end('ok');
421 * });
422 * ```
423 *
424 * `Content-Length` is given in bytes, not characters. Use `Buffer.byteLength()` to determine the length of the body in bytes. Node.js
425 * does not check whether `Content-Length` and the length of the body which has
426 * been transmitted are equal or not.
427 *
428 * Attempting to set a header field name or value that contains invalid characters
429 * will result in a `TypeError` being thrown.
430 * @since v0.1.30
431 */
432 writeHead(statusCode: number, statusMessage?: string, headers?: OutgoingHttpHeaders | OutgoingHttpHeader[]): this;
433 writeHead(statusCode: number, headers?: OutgoingHttpHeaders | OutgoingHttpHeader[]): this;
434 /**
435 * Sends a HTTP/1.1 102 Processing message to the client, indicating that
436 * the request body should be sent.
437 * @since v10.0.0
438 */
439 writeProcessing(): void;
440 }
441 interface InformationEvent {
442 statusCode: number;
443 statusMessage: string;
444 httpVersion: string;
445 httpVersionMajor: number;
446 httpVersionMinor: number;
447 headers: IncomingHttpHeaders;
448 rawHeaders: string[];
449 }
450 /**
451 * This object is created internally and returned from {@link request}. It
452 * represents an _in-progress_ request whose header has already been queued. The
453 * header is still mutable using the `setHeader(name, value)`,`getHeader(name)`, `removeHeader(name)` API. The actual header will
454 * be sent along with the first data chunk or when calling `request.end()`.
455 *
456 * To get the response, add a listener for `'response'` to the request object.`'response'` will be emitted from the request object when the response
457 * headers have been received. The `'response'` event is executed with one
458 * argument which is an instance of {@link IncomingMessage}.
459 *
460 * During the `'response'` event, one can add listeners to the
461 * response object; particularly to listen for the `'data'` event.
462 *
463 * If no `'response'` handler is added, then the response will be
464 * entirely discarded. However, if a `'response'` event handler is added,
465 * then the data from the response object **must** be consumed, either by
466 * calling `response.read()` whenever there is a `'readable'` event, or
467 * by adding a `'data'` handler, or by calling the `.resume()` method.
468 * Until the data is consumed, the `'end'` event will not fire. Also, until
469 * the data is read it will consume memory that can eventually lead to a
470 * 'process out of memory' error.
471 *
472 * For backward compatibility, `res` will only emit `'error'` if there is an`'error'` listener registered.
473 *
474 * Node.js does not check whether Content-Length and the length of the
475 * body which has been transmitted are equal or not.
476 * @since v0.1.17
477 */
478 class ClientRequest extends OutgoingMessage {
479 /**
480 * The `request.aborted` property will be `true` if the request has
481 * been aborted.
482 * @since v0.11.14
483 */
484 aborted: boolean;
485 /**
486 * The request host.
487 * @since v14.5.0, v12.19.0
488 */
489 host: string;
490 /**
491 * The request protocol.
492 * @since v14.5.0, v12.19.0
493 */
494 protocol: string;
495 constructor(url: string | URL | ClientRequestArgs, cb?: (res: IncomingMessage) => void);
496 /**
497 * The request method.
498 * @since v0.1.97
499 */
500 method: string;
501 /**
502 * The request path.
503 * @since v0.4.0
504 */
505 path: string;
506 /**
507 * Marks the request as aborting. Calling this will cause remaining data
508 * in the response to be dropped and the socket to be destroyed.
509 * @since v0.3.8
510 * @deprecated Since v14.1.0,v13.14.0 - Use `destroy` instead.
511 */
512 abort(): void;
513 onSocket(socket: Socket): void;
514 /**
515 * Once a socket is assigned to this request and is connected `socket.setTimeout()` will be called.
516 * @since v0.5.9
517 * @param timeout Milliseconds before a request times out.
518 * @param callback Optional function to be called when a timeout occurs. Same as binding to the `'timeout'` event.
519 */
520 setTimeout(timeout: number, callback?: () => void): this;
521 /**
522 * Once a socket is assigned to this request and is connected `socket.setNoDelay()` will be called.
523 * @since v0.5.9
524 */
525 setNoDelay(noDelay?: boolean): void;
526 /**
527 * Once a socket is assigned to this request and is connected `socket.setKeepAlive()` will be called.
528 * @since v0.5.9
529 */
530 setSocketKeepAlive(enable?: boolean, initialDelay?: number): void;
531 /**
532 * Returns an array containing the unique names of the current outgoing raw
533 * headers. Header names are returned with their exact casing being set.
534 *
535 * ```js
536 * request.setHeader('Foo', 'bar');
537 * request.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);
538 *
539 * const headerNames = request.getRawHeaderNames();
540 * // headerNames === ['Foo', 'Set-Cookie']
541 * ```
542 * @since v15.13.0
543 */
544 getRawHeaderNames(): string[];
545 addListener(event: 'abort', listener: () => void): this;
546 addListener(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this;
547 addListener(event: 'continue', listener: () => void): this;
548 addListener(event: 'information', listener: (info: InformationEvent) => void): this;
549 addListener(event: 'response', listener: (response: IncomingMessage) => void): this;
550 addListener(event: 'socket', listener: (socket: Socket) => void): this;
551 addListener(event: 'timeout', listener: () => void): this;
552 addListener(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this;
553 addListener(event: 'close', listener: () => void): this;
554 addListener(event: 'drain', listener: () => void): this;
555 addListener(event: 'error', listener: (err: Error) => void): this;
556 addListener(event: 'finish', listener: () => void): this;
557 addListener(event: 'pipe', listener: (src: stream.Readable) => void): this;
558 addListener(event: 'unpipe', listener: (src: stream.Readable) => void): this;
559 addListener(event: string | symbol, listener: (...args: any[]) => void): this;
560 on(event: 'abort', listener: () => void): this;
561 on(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this;
562 on(event: 'continue', listener: () => void): this;
563 on(event: 'information', listener: (info: InformationEvent) => void): this;
564 on(event: 'response', listener: (response: IncomingMessage) => void): this;
565 on(event: 'socket', listener: (socket: Socket) => void): this;
566 on(event: 'timeout', listener: () => void): this;
567 on(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this;
568 on(event: 'close', listener: () => void): this;
569 on(event: 'drain', listener: () => void): this;
570 on(event: 'error', listener: (err: Error) => void): this;
571 on(event: 'finish', listener: () => void): this;
572 on(event: 'pipe', listener: (src: stream.Readable) => void): this;
573 on(event: 'unpipe', listener: (src: stream.Readable) => void): this;
574 on(event: string | symbol, listener: (...args: any[]) => void): this;
575 once(event: 'abort', listener: () => void): this;
576 once(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this;
577 once(event: 'continue', listener: () => void): this;
578 once(event: 'information', listener: (info: InformationEvent) => void): this;
579 once(event: 'response', listener: (response: IncomingMessage) => void): this;
580 once(event: 'socket', listener: (socket: Socket) => void): this;
581 once(event: 'timeout', listener: () => void): this;
582 once(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this;
583 once(event: 'close', listener: () => void): this;
584 once(event: 'drain', listener: () => void): this;
585 once(event: 'error', listener: (err: Error) => void): this;
586 once(event: 'finish', listener: () => void): this;
587 once(event: 'pipe', listener: (src: stream.Readable) => void): this;
588 once(event: 'unpipe', listener: (src: stream.Readable) => void): this;
589 once(event: string | symbol, listener: (...args: any[]) => void): this;
590 prependListener(event: 'abort', listener: () => void): this;
591 prependListener(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this;
592 prependListener(event: 'continue', listener: () => void): this;
593 prependListener(event: 'information', listener: (info: InformationEvent) => void): this;
594 prependListener(event: 'response', listener: (response: IncomingMessage) => void): this;
595 prependListener(event: 'socket', listener: (socket: Socket) => void): this;
596 prependListener(event: 'timeout', listener: () => void): this;
597 prependListener(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this;
598 prependListener(event: 'close', listener: () => void): this;
599 prependListener(event: 'drain', listener: () => void): this;
600 prependListener(event: 'error', listener: (err: Error) => void): this;
601 prependListener(event: 'finish', listener: () => void): this;
602 prependListener(event: 'pipe', listener: (src: stream.Readable) => void): this;
603 prependListener(event: 'unpipe', listener: (src: stream.Readable) => void): this;
604 prependListener(event: string | symbol, listener: (...args: any[]) => void): this;
605 prependOnceListener(event: 'abort', listener: () => void): this;
606 prependOnceListener(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this;
607 prependOnceListener(event: 'continue', listener: () => void): this;
608 prependOnceListener(event: 'information', listener: (info: InformationEvent) => void): this;
609 prependOnceListener(event: 'response', listener: (response: IncomingMessage) => void): this;
610 prependOnceListener(event: 'socket', listener: (socket: Socket) => void): this;
611 prependOnceListener(event: 'timeout', listener: () => void): this;
612 prependOnceListener(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this;
613 prependOnceListener(event: 'close', listener: () => void): this;
614 prependOnceListener(event: 'drain', listener: () => void): this;
615 prependOnceListener(event: 'error', listener: (err: Error) => void): this;
616 prependOnceListener(event: 'finish', listener: () => void): this;
617 prependOnceListener(event: 'pipe', listener: (src: stream.Readable) => void): this;
618 prependOnceListener(event: 'unpipe', listener: (src: stream.Readable) => void): this;
619 prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this;
620 }
621 /**
622 * An `IncomingMessage` object is created by {@link Server} or {@link ClientRequest} and passed as the first argument to the `'request'` and `'response'` event respectively. It may be used to
623 * access response
624 * status, headers and data.
625 *
626 * Different from its `socket` value which is a subclass of `<stream.Duplex>`, the`IncomingMessage` itself extends `<stream.Readable>` and is created separately to
627 * parse and emit the incoming HTTP headers and payload, as the underlying socket
628 * may be reused multiple times in case of keep-alive.
629 * @since v0.1.17
630 */
631 class IncomingMessage extends stream.Readable {
632 constructor(socket: Socket);
633 /**
634 * The `message.aborted` property will be `true` if the request has
635 * been aborted.
636 * @since v10.1.0
637 */
638 aborted: boolean;
639 /**
640 * In case of server request, the HTTP version sent by the client. In the case of
641 * client response, the HTTP version of the connected-to server.
642 * Probably either `'1.1'` or `'1.0'`.
643 *
644 * Also `message.httpVersionMajor` is the first integer and`message.httpVersionMinor` is the second.
645 * @since v0.1.1
646 */
647 httpVersion: string;
648 httpVersionMajor: number;
649 httpVersionMinor: number;
650 /**
651 * The `message.complete` property will be `true` if a complete HTTP message has
652 * been received and successfully parsed.
653 *
654 * This property is particularly useful as a means of determining if a client or
655 * server fully transmitted a message before a connection was terminated:
656 *
657 * ```js
658 * const req = http.request({
659 * host: '127.0.0.1',
660 * port: 8080,
661 * method: 'POST'
662 * }, (res) => {
663 * res.resume();
664 * res.on('end', () => {
665 * if (!res.complete)
666 * console.error(
667 * 'The connection was terminated while the message was still being sent');
668 * });
669 * });
670 * ```
671 * @since v0.3.0
672 */
673 complete: boolean;
674 /**
675 * Alias for `message.socket`.
676 * @since v0.1.90
677 * @deprecated Since v16.0.0 - Use `socket`.
678 */
679 connection: Socket;
680 /**
681 * The `net.Socket` object associated with the connection.
682 *
683 * With HTTPS support, use `request.socket.getPeerCertificate()` to obtain the
684 * client's authentication details.
685 *
686 * This property is guaranteed to be an instance of the `<net.Socket>` class,
687 * a subclass of `<stream.Duplex>`, unless the user specified a socket
688 * type other than `<net.Socket>`.
689 * @since v0.3.0
690 */
691 socket: Socket;
692 /**
693 * The request/response headers object.
694 *
695 * Key-value pairs of header names and values. Header names are lower-cased.
696 *
697 * ```js
698 * // Prints something like:
699 * //
700 * // { 'user-agent': 'curl/7.22.0',
701 * // host: '127.0.0.1:8000',
702 * // accept: '*' }
703 * console.log(request.headers);
704 * ```
705 *
706 * Duplicates in raw headers are handled in the following ways, depending on the
707 * header name:
708 *
709 * * Duplicates of `age`, `authorization`, `content-length`, `content-type`,`etag`, `expires`, `from`, `host`, `if-modified-since`, `if-unmodified-since`,`last-modified`, `location`,
710 * `max-forwards`, `proxy-authorization`, `referer`,`retry-after`, `server`, or `user-agent` are discarded.
711 * * `set-cookie` is always an array. Duplicates are added to the array.
712 * * For duplicate `cookie` headers, the values are joined together with '; '.
713 * * For all other headers, the values are joined together with ', '.
714 * @since v0.1.5
715 */
716 headers: IncomingHttpHeaders;
717 /**
718 * The raw request/response headers list exactly as they were received.
719 *
720 * The keys and values are in the same list. It is _not_ a
721 * list of tuples. So, the even-numbered offsets are key values, and the
722 * odd-numbered offsets are the associated values.
723 *
724 * Header names are not lowercased, and duplicates are not merged.
725 *
726 * ```js
727 * // Prints something like:
728 * //
729 * // [ 'user-agent',
730 * // 'this is invalid because there can be only one',
731 * // 'User-Agent',
732 * // 'curl/7.22.0',
733 * // 'Host',
734 * // '127.0.0.1:8000',
735 * // 'ACCEPT',
736 * // '*' ]
737 * console.log(request.rawHeaders);
738 * ```
739 * @since v0.11.6
740 */
741 rawHeaders: string[];
742 /**
743 * The request/response trailers object. Only populated at the `'end'` event.
744 * @since v0.3.0
745 */
746 trailers: NodeJS.Dict<string>;
747 /**
748 * The raw request/response trailer keys and values exactly as they were
749 * received. Only populated at the `'end'` event.
750 * @since v0.11.6
751 */
752 rawTrailers: string[];
753 /**
754 * Calls `message.socket.setTimeout(msecs, callback)`.
755 * @since v0.5.9
756 */
757 setTimeout(msecs: number, callback?: () => void): this;
758 /**
759 * **Only valid for request obtained from {@link Server}.**
760 *
761 * The request method as a string. Read only. Examples: `'GET'`, `'DELETE'`.
762 * @since v0.1.1
763 */
764 method?: string | undefined;
765 /**
766 * **Only valid for request obtained from {@link Server}.**
767 *
768 * Request URL string. This contains only the URL that is present in the actual
769 * HTTP request. Take the following request:
770 *
771 * ```http
772 * GET /status?name=ryan HTTP/1.1
773 * Accept: text/plain
774 * ```
775 *
776 * To parse the URL into its parts:
777 *
778 * ```js
779 * new URL(request.url, `http://${request.headers.host}`);
780 * ```
781 *
782 * When `request.url` is `'/status?name=ryan'` and`request.headers.host` is `'localhost:3000'`:
783 *
784 * ```console
785 * $ node
786 * > new URL(request.url, `http://${request.headers.host}`)
787 * URL {
788 * href: 'http://localhost:3000/status?name=ryan',
789 * origin: 'http://localhost:3000',
790 * protocol: 'http:',
791 * username: '',
792 * password: '',
793 * host: 'localhost:3000',
794 * hostname: 'localhost',
795 * port: '3000',
796 * pathname: '/status',
797 * search: '?name=ryan',
798 * searchParams: URLSearchParams { 'name' => 'ryan' },
799 * hash: ''
800 * }
801 * ```
802 * @since v0.1.90
803 */
804 url?: string | undefined;
805 /**
806 * **Only valid for response obtained from {@link ClientRequest}.**
807 *
808 * The 3-digit HTTP response status code. E.G. `404`.
809 * @since v0.1.1
810 */
811 statusCode?: number | undefined;
812 /**
813 * **Only valid for response obtained from {@link ClientRequest}.**
814 *
815 * The HTTP response status message (reason phrase). E.G. `OK` or `Internal Server Error`.
816 * @since v0.11.10
817 */
818 statusMessage?: string | undefined;
819 /**
820 * 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
821 * as an argument to any listeners on the event.
822 * @since v0.3.0
823 */
824 destroy(error?: Error): void;
825 }
826 interface AgentOptions {
827 /**
828 * Keep sockets around in a pool to be used by other requests in the future. Default = false
829 */
830 keepAlive?: boolean | undefined;
831 /**
832 * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000.
833 * Only relevant if keepAlive is set to true.
834 */
835 keepAliveMsecs?: number | undefined;
836 /**
837 * Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity
838 */
839 maxSockets?: number | undefined;
840 /**
841 * Maximum number of sockets allowed for all hosts in total. Each request will use a new socket until the maximum is reached. Default: Infinity.
842 */
843 maxTotalSockets?: number | undefined;
844 /**
845 * Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256.
846 */
847 maxFreeSockets?: number | undefined;
848 /**
849 * Socket timeout in milliseconds. This will set the timeout after the socket is connected.
850 */
851 timeout?: number | undefined;
852 /**
853 * Scheduling strategy to apply when picking the next free socket to use.
854 * @default `lifo`
855 */
856 scheduling?: 'fifo' | 'lifo' | undefined;
857 }
858 /**
859 * An `Agent` is responsible for managing connection persistence
860 * and reuse for HTTP clients. It maintains a queue of pending requests
861 * for a given host and port, reusing a single socket connection for each
862 * until the queue is empty, at which time the socket is either destroyed
863 * or put into a pool where it is kept to be used again for requests to the
864 * same host and port. Whether it is destroyed or pooled depends on the`keepAlive` `option`.
865 *
866 * Pooled connections have TCP Keep-Alive enabled for them, but servers may
867 * still close idle connections, in which case they will be removed from the
868 * pool and a new connection will be made when a new HTTP request is made for
869 * that host and port. Servers may also refuse to allow multiple requests
870 * over the same connection, in which case the connection will have to be
871 * remade for every request and cannot be pooled. The `Agent` will still make
872 * the requests to that server, but each one will occur over a new connection.
873 *
874 * When a connection is closed by the client or the server, it is removed
875 * from the pool. Any unused sockets in the pool will be unrefed so as not
876 * to keep the Node.js process running when there are no outstanding requests.
877 * (see `socket.unref()`).
878 *
879 * It is good practice, to `destroy()` an `Agent` instance when it is no
880 * longer in use, because unused sockets consume OS resources.
881 *
882 * Sockets are removed from an agent when the socket emits either
883 * a `'close'` event or an `'agentRemove'` event. When intending to keep one
884 * HTTP request open for a long time without keeping it in the agent, something
885 * like the following may be done:
886 *
887 * ```js
888 * http.get(options, (res) => {
889 * // Do stuff
890 * }).on('socket', (socket) => {
891 * socket.emit('agentRemove');
892 * });
893 * ```
894 *
895 * 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
896 * will be used
897 * for the client connection.
898 *
899 * `agent:false`:
900 *
901 * ```js
902 * http.get({
903 * hostname: 'localhost',
904 * port: 80,
905 * path: '/',
906 * agent: false // Create a new agent just for this one request
907 * }, (res) => {
908 * // Do stuff with response
909 * });
910 * ```
911 * @since v0.3.4
912 */
913 class Agent {
914 /**
915 * By default set to 256\. For agents with `keepAlive` enabled, this
916 * sets the maximum number of sockets that will be left open in the free
917 * state.
918 * @since v0.11.7
919 */
920 maxFreeSockets: number;
921 /**
922 * By default set to `Infinity`. Determines how many concurrent sockets the agent
923 * can have open per origin. Origin is the returned value of `agent.getName()`.
924 * @since v0.3.6
925 */
926 maxSockets: number;
927 /**
928 * By default set to `Infinity`. Determines how many concurrent sockets the agent
929 * can have open. Unlike `maxSockets`, this parameter applies across all origins.
930 * @since v14.5.0, v12.19.0
931 */
932 maxTotalSockets: number;
933 /**
934 * An object which contains arrays of sockets currently awaiting use by
935 * the agent when `keepAlive` is enabled. Do not modify.
936 *
937 * Sockets in the `freeSockets` list will be automatically destroyed and
938 * removed from the array on `'timeout'`.
939 * @since v0.11.4
940 */
941 readonly freeSockets: NodeJS.ReadOnlyDict<Socket[]>;
942 /**
943 * An object which contains arrays of sockets currently in use by the
944 * agent. Do not modify.
945 * @since v0.3.6
946 */
947 readonly sockets: NodeJS.ReadOnlyDict<Socket[]>;
948 /**
949 * An object which contains queues of requests that have not yet been assigned to
950 * sockets. Do not modify.
951 * @since v0.5.9
952 */
953 readonly requests: NodeJS.ReadOnlyDict<IncomingMessage[]>;
954 constructor(opts?: AgentOptions);
955 /**
956 * Destroy any sockets that are currently in use by the agent.
957 *
958 * It is usually not necessary to do this. However, if using an
959 * agent with `keepAlive` enabled, then it is best to explicitly shut down
960 * the agent when it is no longer needed. Otherwise,
961 * sockets might stay open for quite a long time before the server
962 * terminates them.
963 * @since v0.11.4
964 */
965 destroy(): void;
966 }
967 const METHODS: string[];
968 const STATUS_CODES: {
969 [errorCode: number]: string | undefined;
970 [errorCode: string]: string | undefined;
971 };
972 /**
973 * Returns a new instance of {@link Server}.
974 *
975 * The `requestListener` is a function which is automatically
976 * added to the `'request'` event.
977 * @since v0.1.13
978 */
979 function createServer(requestListener?: RequestListener): Server;
980 function createServer(options: ServerOptions, requestListener?: RequestListener): Server;
981 // although RequestOptions are passed as ClientRequestArgs to ClientRequest directly,
982 // create interface RequestOptions would make the naming more clear to developers
983 interface RequestOptions extends ClientRequestArgs {}
984 /**
985 * Node.js maintains several connections per server to make HTTP requests.
986 * This function allows one to transparently issue requests.
987 *
988 * `url` can be a string or a `URL` object. If `url` is a
989 * string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object.
990 *
991 * If both `url` and `options` are specified, the objects are merged, with the`options` properties taking precedence.
992 *
993 * The optional `callback` parameter will be added as a one-time listener for
994 * the `'response'` event.
995 *
996 * `http.request()` returns an instance of the {@link ClientRequest} class. The `ClientRequest` instance is a writable stream. If one needs to
997 * upload a file with a POST request, then write to the `ClientRequest` object.
998 *
999 * ```js
1000 * const http = require('http');
1001 *
1002 * const postData = JSON.stringify({
1003 * 'msg': 'Hello World!'
1004 * });
1005 *
1006 * const options = {
1007 * hostname: 'www.google.com',
1008 * port: 80,
1009 * path: '/upload',
1010 * method: 'POST',
1011 * headers: {
1012 * 'Content-Type': 'application/json',
1013 * 'Content-Length': Buffer.byteLength(postData)
1014 * }
1015 * };
1016 *
1017 * const req = http.request(options, (res) => {
1018 * console.log(`STATUS: ${res.statusCode}`);
1019 * console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
1020 * res.setEncoding('utf8');
1021 * res.on('data', (chunk) => {
1022 * console.log(`BODY: ${chunk}`);
1023 * });
1024 * res.on('end', () => {
1025 * console.log('No more data in response.');
1026 * });
1027 * });
1028 *
1029 * req.on('error', (e) => {
1030 * console.error(`problem with request: ${e.message}`);
1031 * });
1032 *
1033 * // Write data to request body
1034 * req.write(postData);
1035 * req.end();
1036 * ```
1037 *
1038 * In the example `req.end()` was called. With `http.request()` one
1039 * must always call `req.end()` to signify the end of the request -
1040 * even if there is no data being written to the request body.
1041 *
1042 * If any error is encountered during the request (be that with DNS resolution,
1043 * TCP level errors, or actual HTTP parse errors) an `'error'` event is emitted
1044 * on the returned request object. As with all `'error'` events, if no listeners
1045 * are registered the error will be thrown.
1046 *
1047 * There are a few special headers that should be noted.
1048 *
1049 * * Sending a 'Connection: keep-alive' will notify Node.js that the connection to
1050 * the server should be persisted until the next request.
1051 * * Sending a 'Content-Length' header will disable the default chunked encoding.
1052 * * Sending an 'Expect' header will immediately send the request headers.
1053 * Usually, when sending 'Expect: 100-continue', both a timeout and a listener
1054 * for the `'continue'` event should be set. See RFC 2616 Section 8.2.3 for more
1055 * information.
1056 * * Sending an Authorization header will override using the `auth` option
1057 * to compute basic authentication.
1058 *
1059 * Example using a `URL` as `options`:
1060 *
1061 * ```js
1062 * const options = new URL('http://abc:xyz@example.com');
1063 *
1064 * const req = http.request(options, (res) => {
1065 * // ...
1066 * });
1067 * ```
1068 *
1069 * In a successful request, the following events will be emitted in the following
1070 * order:
1071 *
1072 * * `'socket'`
1073 * * `'response'`
1074 * * `'data'` any number of times, on the `res` object
1075 * (`'data'` will not be emitted at all if the response body is empty, for
1076 * instance, in most redirects)
1077 * * `'end'` on the `res` object
1078 * * `'close'`
1079 *
1080 * In the case of a connection error, the following events will be emitted:
1081 *
1082 * * `'socket'`
1083 * * `'error'`
1084 * * `'close'`
1085 *
1086 * In the case of a premature connection close before the response is received,
1087 * the following events will be emitted in the following order:
1088 *
1089 * * `'socket'`
1090 * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'`
1091 * * `'close'`
1092 *
1093 * In the case of a premature connection close after the response is received,
1094 * the following events will be emitted in the following order:
1095 *
1096 * * `'socket'`
1097 * * `'response'`
1098 * * `'data'` any number of times, on the `res` object
1099 * * (connection closed here)
1100 * * `'aborted'` on the `res` object
1101 * * `'error'` on the `res` object with an error with message`'Error: aborted'` and code `'ECONNRESET'`.
1102 * * `'close'`
1103 * * `'close'` on the `res` object
1104 *
1105 * If `req.destroy()` is called before a socket is assigned, the following
1106 * events will be emitted in the following order:
1107 *
1108 * * (`req.destroy()` called here)
1109 * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'`
1110 * * `'close'`
1111 *
1112 * If `req.destroy()` is called before the connection succeeds, the following
1113 * events will be emitted in the following order:
1114 *
1115 * * `'socket'`
1116 * * (`req.destroy()` called here)
1117 * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'`
1118 * * `'close'`
1119 *
1120 * If `req.destroy()` is called after the response is received, the following
1121 * events will be emitted in the following order:
1122 *
1123 * * `'socket'`
1124 * * `'response'`
1125 * * `'data'` any number of times, on the `res` object
1126 * * (`req.destroy()` called here)
1127 * * `'aborted'` on the `res` object
1128 * * `'error'` on the `res` object with an error with message`'Error: aborted'` and code `'ECONNRESET'`.
1129 * * `'close'`
1130 * * `'close'` on the `res` object
1131 *
1132 * If `req.abort()` is called before a socket is assigned, the following
1133 * events will be emitted in the following order:
1134 *
1135 * * (`req.abort()` called here)
1136 * * `'abort'`
1137 * * `'close'`
1138 *
1139 * If `req.abort()` is called before the connection succeeds, the following
1140 * events will be emitted in the following order:
1141 *
1142 * * `'socket'`
1143 * * (`req.abort()` called here)
1144 * * `'abort'`
1145 * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'`
1146 * * `'close'`
1147 *
1148 * If `req.abort()` is called after the response is received, the following
1149 * events will be emitted in the following order:
1150 *
1151 * * `'socket'`
1152 * * `'response'`
1153 * * `'data'` any number of times, on the `res` object
1154 * * (`req.abort()` called here)
1155 * * `'abort'`
1156 * * `'aborted'` on the `res` object
1157 * * `'error'` on the `res` object with an error with message`'Error: aborted'` and code `'ECONNRESET'`.
1158 * * `'close'`
1159 * * `'close'` on the `res` object
1160 *
1161 * Setting the `timeout` option or using the `setTimeout()` function will
1162 * not abort the request or do anything besides add a `'timeout'` event.
1163 *
1164 * Passing an `AbortSignal` and then calling `abort` on the corresponding`AbortController` will behave the same way as calling `.destroy()` on the
1165 * request itself.
1166 * @since v0.3.6
1167 */
1168 function request(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest;
1169 function request(url: string | URL, options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest;
1170 /**
1171 * Since most requests are GET requests without bodies, Node.js provides this
1172 * convenience method. The only difference between this method and {@link request} is that it sets the method to GET and calls `req.end()`automatically. The callback must take care to consume the
1173 * response
1174 * data for reasons stated in {@link ClientRequest} section.
1175 *
1176 * The `callback` is invoked with a single argument that is an instance of {@link IncomingMessage}.
1177 *
1178 * JSON fetching example:
1179 *
1180 * ```js
1181 * http.get('http://localhost:8000/', (res) => {
1182 * const { statusCode } = res;
1183 * const contentType = res.headers['content-type'];
1184 *
1185 * let error;
1186 * // Any 2xx status code signals a successful response but
1187 * // here we're only checking for 200.
1188 * if (statusCode !== 200) {
1189 * error = new Error('Request Failed.\n' +
1190 * `Status Code: ${statusCode}`);
1191 * } else if (!/^application\/json/.test(contentType)) {
1192 * error = new Error('Invalid content-type.\n' +
1193 * `Expected application/json but received ${contentType}`);
1194 * }
1195 * if (error) {
1196 * console.error(error.message);
1197 * // Consume response data to free up memory
1198 * res.resume();
1199 * return;
1200 * }
1201 *
1202 * res.setEncoding('utf8');
1203 * let rawData = '';
1204 * res.on('data', (chunk) => { rawData += chunk; });
1205 * res.on('end', () => {
1206 * try {
1207 * const parsedData = JSON.parse(rawData);
1208 * console.log(parsedData);
1209 * } catch (e) {
1210 * console.error(e.message);
1211 * }
1212 * });
1213 * }).on('error', (e) => {
1214 * console.error(`Got error: ${e.message}`);
1215 * });
1216 *
1217 * // Create a local server to receive data from
1218 * const server = http.createServer((req, res) => {
1219 * res.writeHead(200, { 'Content-Type': 'application/json' });
1220 * res.end(JSON.stringify({
1221 * data: 'Hello World!'
1222 * }));
1223 * });
1224 *
1225 * server.listen(8000);
1226 * ```
1227 * @since v0.3.6
1228 * @param options Accepts the same `options` as {@link request}, with the `method` always set to `GET`. Properties that are inherited from the prototype are ignored.
1229 */
1230 function get(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest;
1231 function get(url: string | URL, options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest;
1232 let globalAgent: Agent;
1233 /**
1234 * Read-only property specifying the maximum allowed size of HTTP headers in bytes.
1235 * Defaults to 16KB. Configurable using the `--max-http-header-size` CLI option.
1236 */
1237 const maxHeaderSize: number;
1238}
1239declare module 'node:http' {
1240 export * from 'http';
1241}
1242
\No newline at end of file