UNPKG

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