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