1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 |
|
31 |
|
32 |
|
33 |
|
34 |
|
35 |
|
36 |
|
37 |
|
38 |
|
39 |
|
40 |
|
41 |
|
42 | declare 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 |
|
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 |
|
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 |
|
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 |
|
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 |
|
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 |
|
334 |
|
335 | finished: boolean;
|
336 | |
337 |
|
338 |
|
339 |
|
340 | readonly headersSent: boolean;
|
341 | |
342 |
|
343 |
|
344 |
|
345 |
|
346 | readonly connection: Socket | null;
|
347 | |
348 |
|
349 |
|
350 |
|
351 |
|
352 |
|
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 | *
|
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 | /**
|
625 | * Whether the request is send through a reused socket.
|
626 | * @since v13.0.0, v12.16.0
|
627 | */
|
628 | reusedSocket: boolean;
|
629 | /**
|
630 | * Limits maximum response headers count. If set to 0, no limit will be applied.
|
631 | * @default 2000
|
632 | */
|
633 | maxHeadersCount: number;
|
634 | constructor(url: string | URL | ClientRequestArgs, cb?: (res: IncomingMessage) => void);
|
635 | /**
|
636 | * The request method.
|
637 | * @since v0.1.97
|
638 | */
|
639 | method: string;
|
640 | /**
|
641 | * The request path.
|
642 | * @since v0.4.0
|
643 | */
|
644 | path: string;
|
645 | /**
|
646 | * Marks the request as aborting. Calling this will cause remaining data
|
647 | * in the response to be dropped and the socket to be destroyed.
|
648 | * @since v0.3.8
|
649 | * @deprecated Since v14.1.0,v13.14.0 - Use `destroy` instead.
|
650 | */
|
651 | abort(): void;
|
652 | onSocket(socket: Socket): void;
|
653 | /**
|
654 | * Once a socket is assigned to this request and is connected `socket.setTimeout()` will be called.
|
655 | * @since v0.5.9
|
656 | * @param timeout Milliseconds before a request times out.
|
657 | * @param callback Optional function to be called when a timeout occurs. Same as binding to the `'timeout'` event.
|
658 | */
|
659 | setTimeout(timeout: number, callback?: () => void): this;
|
660 | /**
|
661 | * Once a socket is assigned to this request and is connected `socket.setNoDelay()` will be called.
|
662 | * @since v0.5.9
|
663 | */
|
664 | setNoDelay(noDelay?: boolean): void;
|
665 | /**
|
666 | * Once a socket is assigned to this request and is connected `socket.setKeepAlive()` will be called.
|
667 | * @since v0.5.9
|
668 | */
|
669 | setSocketKeepAlive(enable?: boolean, initialDelay?: number): void;
|
670 | /**
|
671 | * Returns an array containing the unique names of the current outgoing raw
|
672 | * headers. Header names are returned with their exact casing being set.
|
673 | *
|
674 | * ```js
|
675 | * request.setHeader('Foo', 'bar');
|
676 | * request.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);
|
677 | *
|
678 | * const headerNames = request.getRawHeaderNames();
|
679 | *
|
680 | * ```
|
681 | * @since v15.13.0, v14.17.0
|
682 | */
|
683 | getRawHeaderNames(): string[];
|
684 | /**
|
685 | * @deprecated
|
686 | */
|
687 | addListener(event: 'abort', listener: () => void): this;
|
688 | addListener(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this;
|
689 | addListener(event: 'continue', listener: () => void): this;
|
690 | addListener(event: 'information', listener: (info: InformationEvent) => void): this;
|
691 | addListener(event: 'response', listener: (response: IncomingMessage) => void): this;
|
692 | addListener(event: 'socket', listener: (socket: Socket) => void): this;
|
693 | addListener(event: 'timeout', listener: () => void): this;
|
694 | addListener(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this;
|
695 | addListener(event: 'close', listener: () => void): this;
|
696 | addListener(event: 'drain', listener: () => void): this;
|
697 | addListener(event: 'error', listener: (err: Error) => void): this;
|
698 | addListener(event: 'finish', listener: () => void): this;
|
699 | addListener(event: 'pipe', listener: (src: stream.Readable) => void): this;
|
700 | addListener(event: 'unpipe', listener: (src: stream.Readable) => void): this;
|
701 | addListener(event: string | symbol, listener: (...args: any[]) => void): this;
|
702 | /**
|
703 | * @deprecated
|
704 | */
|
705 | on(event: 'abort', listener: () => void): this;
|
706 | on(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this;
|
707 | on(event: 'continue', listener: () => void): this;
|
708 | on(event: 'information', listener: (info: InformationEvent) => void): this;
|
709 | on(event: 'response', listener: (response: IncomingMessage) => void): this;
|
710 | on(event: 'socket', listener: (socket: Socket) => void): this;
|
711 | on(event: 'timeout', listener: () => void): this;
|
712 | on(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this;
|
713 | on(event: 'close', listener: () => void): this;
|
714 | on(event: 'drain', listener: () => void): this;
|
715 | on(event: 'error', listener: (err: Error) => void): this;
|
716 | on(event: 'finish', listener: () => void): this;
|
717 | on(event: 'pipe', listener: (src: stream.Readable) => void): this;
|
718 | on(event: 'unpipe', listener: (src: stream.Readable) => void): this;
|
719 | on(event: string | symbol, listener: (...args: any[]) => void): this;
|
720 | /**
|
721 | * @deprecated
|
722 | */
|
723 | once(event: 'abort', listener: () => void): this;
|
724 | once(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this;
|
725 | once(event: 'continue', listener: () => void): this;
|
726 | once(event: 'information', listener: (info: InformationEvent) => void): this;
|
727 | once(event: 'response', listener: (response: IncomingMessage) => void): this;
|
728 | once(event: 'socket', listener: (socket: Socket) => void): this;
|
729 | once(event: 'timeout', listener: () => void): this;
|
730 | once(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this;
|
731 | once(event: 'close', listener: () => void): this;
|
732 | once(event: 'drain', listener: () => void): this;
|
733 | once(event: 'error', listener: (err: Error) => void): this;
|
734 | once(event: 'finish', listener: () => void): this;
|
735 | once(event: 'pipe', listener: (src: stream.Readable) => void): this;
|
736 | once(event: 'unpipe', listener: (src: stream.Readable) => void): this;
|
737 | once(event: string | symbol, listener: (...args: any[]) => void): this;
|
738 | /**
|
739 | * @deprecated
|
740 | */
|
741 | prependListener(event: 'abort', listener: () => void): this;
|
742 | prependListener(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this;
|
743 | prependListener(event: 'continue', listener: () => void): this;
|
744 | prependListener(event: 'information', listener: (info: InformationEvent) => void): this;
|
745 | prependListener(event: 'response', listener: (response: IncomingMessage) => void): this;
|
746 | prependListener(event: 'socket', listener: (socket: Socket) => void): this;
|
747 | prependListener(event: 'timeout', listener: () => void): this;
|
748 | prependListener(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this;
|
749 | prependListener(event: 'close', listener: () => void): this;
|
750 | prependListener(event: 'drain', listener: () => void): this;
|
751 | prependListener(event: 'error', listener: (err: Error) => void): this;
|
752 | prependListener(event: 'finish', listener: () => void): this;
|
753 | prependListener(event: 'pipe', listener: (src: stream.Readable) => void): this;
|
754 | prependListener(event: 'unpipe', listener: (src: stream.Readable) => void): this;
|
755 | prependListener(event: string | symbol, listener: (...args: any[]) => void): this;
|
756 | /**
|
757 | * @deprecated
|
758 | */
|
759 | prependOnceListener(event: 'abort', listener: () => void): this;
|
760 | prependOnceListener(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this;
|
761 | prependOnceListener(event: 'continue', listener: () => void): this;
|
762 | prependOnceListener(event: 'information', listener: (info: InformationEvent) => void): this;
|
763 | prependOnceListener(event: 'response', listener: (response: IncomingMessage) => void): this;
|
764 | prependOnceListener(event: 'socket', listener: (socket: Socket) => void): this;
|
765 | prependOnceListener(event: 'timeout', listener: () => void): this;
|
766 | prependOnceListener(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this;
|
767 | prependOnceListener(event: 'close', listener: () => void): this;
|
768 | prependOnceListener(event: 'drain', listener: () => void): this;
|
769 | prependOnceListener(event: 'error', listener: (err: Error) => void): this;
|
770 | prependOnceListener(event: 'finish', listener: () => void): this;
|
771 | prependOnceListener(event: 'pipe', listener: (src: stream.Readable) => void): this;
|
772 | prependOnceListener(event: 'unpipe', listener: (src: stream.Readable) => void): this;
|
773 | prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this;
|
774 | }
|
775 | /**
|
776 | * 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
|
777 | * access response
|
778 | * status, headers and data.
|
779 | *
|
780 | * Different from its `socket` value which is a subclass of `stream.Duplex`, the`IncomingMessage` itself extends `stream.Readable` and is created separately to
|
781 | * parse and emit the incoming HTTP headers and payload, as the underlying socket
|
782 | * may be reused multiple times in case of keep-alive.
|
783 | * @since v0.1.17
|
784 | */
|
785 | class IncomingMessage extends stream.Readable {
|
786 | constructor(socket: Socket);
|
787 | /**
|
788 | * The `message.aborted` property will be `true` if the request has
|
789 | * been aborted.
|
790 | * @since v10.1.0
|
791 | * @deprecated Since v17.0.0 - Check `message.destroyed` from [stream.Readable](https://nodejs.org/dist/latest-v17.x/docs/api/stream.html#class-streamreadable).
|
792 | */
|
793 | aborted: boolean;
|
794 | /**
|
795 | * In case of server request, the HTTP version sent by the client. In the case of
|
796 | * client response, the HTTP version of the connected-to server.
|
797 | * Probably either `'1.1'` or `'1.0'`.
|
798 | *
|
799 | * Also `message.httpVersionMajor` is the first integer and`message.httpVersionMinor` is the second.
|
800 | * @since v0.1.1
|
801 | */
|
802 | httpVersion: string;
|
803 | httpVersionMajor: number;
|
804 | httpVersionMinor: number;
|
805 | /**
|
806 | * The `message.complete` property will be `true` if a complete HTTP message has
|
807 | * been received and successfully parsed.
|
808 | *
|
809 | * This property is particularly useful as a means of determining if a client or
|
810 | * server fully transmitted a message before a connection was terminated:
|
811 | *
|
812 | * ```js
|
813 | * const req = http.request({
|
814 | * host: '127.0.0.1',
|
815 | * port: 8080,
|
816 | * method: 'POST'
|
817 | * }, (res) => {
|
818 | * res.resume();
|
819 | * res.on('end', () => {
|
820 | * if (!res.complete)
|
821 | * console.error(
|
822 | * 'The connection was terminated while the message was still being sent');
|
823 | * });
|
824 | * });
|
825 | * ```
|
826 | * @since v0.3.0
|
827 | */
|
828 | complete: boolean;
|
829 | /**
|
830 | * Alias for `message.socket`.
|
831 | * @since v0.1.90
|
832 | * @deprecated Since v16.0.0 - Use `socket`.
|
833 | */
|
834 | connection: Socket;
|
835 | /**
|
836 | * The `net.Socket` object associated with the connection.
|
837 | *
|
838 | * With HTTPS support, use `request.socket.getPeerCertificate()` to obtain the
|
839 | * client's authentication details.
|
840 | *
|
841 | * This property is guaranteed to be an instance of the `net.Socket` class,
|
842 | * a subclass of `stream.Duplex`, unless the user specified a socket
|
843 | * type other than `net.Socket`.
|
844 | * @since v0.3.0
|
845 | */
|
846 | socket: Socket;
|
847 | /**
|
848 | * The request/response headers object.
|
849 | *
|
850 | * Key-value pairs of header names and values. Header names are lower-cased.
|
851 | *
|
852 | * ```js
|
853 | *
|
854 | *
|
855 | *
|
856 | *
|
857 | *
|
858 | * console.log(request.headers);
|
859 | * ```
|
860 | *
|
861 | * Duplicates in raw headers are handled in the following ways, depending on the
|
862 | * header name:
|
863 | *
|
864 | * * Duplicates of `age`, `authorization`, `content-length`, `content-type`,`etag`, `expires`, `from`, `host`, `if-modified-since`, `if-unmodified-since`,`last-modified`, `location`,
|
865 | * `max-forwards`, `proxy-authorization`, `referer`,`retry-after`, `server`, or `user-agent` are discarded.
|
866 | * * `set-cookie` is always an array. Duplicates are added to the array.
|
867 | * * For duplicate `cookie` headers, the values are joined together with '; '.
|
868 | * * For all other headers, the values are joined together with ', '.
|
869 | * @since v0.1.5
|
870 | */
|
871 | headers: IncomingHttpHeaders;
|
872 | /**
|
873 | * The raw request/response headers list exactly as they were received.
|
874 | *
|
875 | * The keys and values are in the same list. It is _not_ a
|
876 | * list of tuples. So, the even-numbered offsets are key values, and the
|
877 | * odd-numbered offsets are the associated values.
|
878 | *
|
879 | * Header names are not lowercased, and duplicates are not merged.
|
880 | *
|
881 | * ```js
|
882 | *
|
883 | *
|
884 | *
|
885 | *
|
886 | *
|
887 | *
|
888 | *
|
889 | *
|
890 | *
|
891 | *
|
892 | * console.log(request.rawHeaders);
|
893 | * ```
|
894 | * @since v0.11.6
|
895 | */
|
896 | rawHeaders: string[];
|
897 | /**
|
898 | * The request/response trailers object. Only populated at the `'end'` event.
|
899 | * @since v0.3.0
|
900 | */
|
901 | trailers: NodeJS.Dict<string>;
|
902 | /**
|
903 | * The raw request/response trailer keys and values exactly as they were
|
904 | * received. Only populated at the `'end'` event.
|
905 | * @since v0.11.6
|
906 | */
|
907 | rawTrailers: string[];
|
908 | /**
|
909 | * Calls `message.socket.setTimeout(msecs, callback)`.
|
910 | * @since v0.5.9
|
911 | */
|
912 | setTimeout(msecs: number, callback?: () => void): this;
|
913 | /**
|
914 | * **Only valid for request obtained from {@link Server}.**
|
915 | *
|
916 | * The request method as a string. Read only. Examples: `'GET'`, `'DELETE'`.
|
917 | * @since v0.1.1
|
918 | */
|
919 | method?: string | undefined;
|
920 | /**
|
921 | * **Only valid for request obtained from {@link Server}.**
|
922 | *
|
923 | * Request URL string. This contains only the URL that is present in the actual
|
924 | * HTTP request. Take the following request:
|
925 | *
|
926 | * ```http
|
927 | * GET /status?name=ryan HTTP/1.1
|
928 | * Accept: text/plain
|
929 | * ```
|
930 | *
|
931 | * To parse the URL into its parts:
|
932 | *
|
933 | * ```js
|
934 | * new URL(request.url, `http://${request.headers.host}`);
|
935 | * ```
|
936 | *
|
937 | * When `request.url` is `'/status?name=ryan'` and`request.headers.host` is `'localhost:3000'`:
|
938 | *
|
939 | * ```console
|
940 | * $ node
|
941 | * > new URL(request.url, `http://${request.headers.host}`)
|
942 | * URL {
|
943 | * href: 'http://localhost:3000/status?name=ryan',
|
944 | * origin: 'http://localhost:3000',
|
945 | * protocol: 'http:',
|
946 | * username: '',
|
947 | * password: '',
|
948 | * host: 'localhost:3000',
|
949 | * hostname: 'localhost',
|
950 | * port: '3000',
|
951 | * pathname: '/status',
|
952 | * search: '?name=ryan',
|
953 | * searchParams: URLSearchParams { 'name' => 'ryan' },
|
954 | * hash: ''
|
955 | * }
|
956 | * ```
|
957 | * @since v0.1.90
|
958 | */
|
959 | url?: string | undefined;
|
960 | /**
|
961 | * **Only valid for response obtained from {@link ClientRequest}.**
|
962 | *
|
963 | * The 3-digit HTTP response status code. E.G. `404`.
|
964 | * @since v0.1.1
|
965 | */
|
966 | statusCode?: number | undefined;
|
967 | /**
|
968 | * **Only valid for response obtained from {@link ClientRequest}.**
|
969 | *
|
970 | * The HTTP response status message (reason phrase). E.G. `OK` or `Internal Server Error`.
|
971 | * @since v0.11.10
|
972 | */
|
973 | statusMessage?: string | undefined;
|
974 | /**
|
975 | * 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
|
976 | * as an argument to any listeners on the event.
|
977 | * @since v0.3.0
|
978 | */
|
979 | destroy(error?: Error): this;
|
980 | }
|
981 | interface AgentOptions extends Partial<TcpSocketConnectOpts> {
|
982 | /**
|
983 | * Keep sockets around in a pool to be used by other requests in the future. Default = false
|
984 | */
|
985 | keepAlive?: boolean | undefined;
|
986 | /**
|
987 | * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000.
|
988 | * Only relevant if keepAlive is set to true.
|
989 | */
|
990 | keepAliveMsecs?: number | undefined;
|
991 | /**
|
992 | * Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity
|
993 | */
|
994 | maxSockets?: number | undefined;
|
995 | /**
|
996 | * Maximum number of sockets allowed for all hosts in total. Each request will use a new socket until the maximum is reached. Default: Infinity.
|
997 | */
|
998 | maxTotalSockets?: number | undefined;
|
999 | /**
|
1000 | * Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256.
|
1001 | */
|
1002 | maxFreeSockets?: number | undefined;
|
1003 | /**
|
1004 | * Socket timeout in milliseconds. This will set the timeout after the socket is connected.
|
1005 | */
|
1006 | timeout?: number | undefined;
|
1007 | /**
|
1008 | * Scheduling strategy to apply when picking the next free socket to use.
|
1009 | * @default `lifo`
|
1010 | */
|
1011 | scheduling?: 'fifo' | 'lifo' | undefined;
|
1012 | }
|
1013 | /**
|
1014 | * An `Agent` is responsible for managing connection persistence
|
1015 | * and reuse for HTTP clients. It maintains a queue of pending requests
|
1016 | * for a given host and port, reusing a single socket connection for each
|
1017 | * until the queue is empty, at which time the socket is either destroyed
|
1018 | * or put into a pool where it is kept to be used again for requests to the
|
1019 | * same host and port. Whether it is destroyed or pooled depends on the`keepAlive` `option`.
|
1020 | *
|
1021 | * Pooled connections have TCP Keep-Alive enabled for them, but servers may
|
1022 | * still close idle connections, in which case they will be removed from the
|
1023 | * pool and a new connection will be made when a new HTTP request is made for
|
1024 | * that host and port. Servers may also refuse to allow multiple requests
|
1025 | * over the same connection, in which case the connection will have to be
|
1026 | * remade for every request and cannot be pooled. The `Agent` will still make
|
1027 | * the requests to that server, but each one will occur over a new connection.
|
1028 | *
|
1029 | * When a connection is closed by the client or the server, it is removed
|
1030 | * from the pool. Any unused sockets in the pool will be unrefed so as not
|
1031 | * to keep the Node.js process running when there are no outstanding requests.
|
1032 | * (see `socket.unref()`).
|
1033 | *
|
1034 | * It is good practice, to `destroy()` an `Agent` instance when it is no
|
1035 | * longer in use, because unused sockets consume OS resources.
|
1036 | *
|
1037 | * Sockets are removed from an agent when the socket emits either
|
1038 | * a `'close'` event or an `'agentRemove'` event. When intending to keep one
|
1039 | * HTTP request open for a long time without keeping it in the agent, something
|
1040 | * like the following may be done:
|
1041 | *
|
1042 | * ```js
|
1043 | * http.get(options, (res) => {
|
1044 | *
|
1045 | * }).on('socket', (socket) => {
|
1046 | * socket.emit('agentRemove');
|
1047 | * });
|
1048 | * ```
|
1049 | *
|
1050 | * 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
|
1051 | * will be used
|
1052 | * for the client connection.
|
1053 | *
|
1054 | * `agent:false`:
|
1055 | *
|
1056 | * ```js
|
1057 | * http.get({
|
1058 | * hostname: 'localhost',
|
1059 | * port: 80,
|
1060 | * path: '/',
|
1061 | * agent: false
|
1062 | * }, (res) => {
|
1063 | *
|
1064 | * });
|
1065 | * ```
|
1066 | * @since v0.3.4
|
1067 | */
|
1068 | class Agent {
|
1069 | /**
|
1070 | * By default set to 256\. For agents with `keepAlive` enabled, this
|
1071 | * sets the maximum number of sockets that will be left open in the free
|
1072 | * state.
|
1073 | * @since v0.11.7
|
1074 | */
|
1075 | maxFreeSockets: number;
|
1076 | /**
|
1077 | * By default set to `Infinity`. Determines how many concurrent sockets the agent
|
1078 | * can have open per origin. Origin is the returned value of `agent.getName()`.
|
1079 | * @since v0.3.6
|
1080 | */
|
1081 | maxSockets: number;
|
1082 | /**
|
1083 | * By default set to `Infinity`. Determines how many concurrent sockets the agent
|
1084 | * can have open. Unlike `maxSockets`, this parameter applies across all origins.
|
1085 | * @since v14.5.0, v12.19.0
|
1086 | */
|
1087 | maxTotalSockets: number;
|
1088 | /**
|
1089 | * An object which contains arrays of sockets currently awaiting use by
|
1090 | * the agent when `keepAlive` is enabled. Do not modify.
|
1091 | *
|
1092 | * Sockets in the `freeSockets` list will be automatically destroyed and
|
1093 | * removed from the array on `'timeout'`.
|
1094 | * @since v0.11.4
|
1095 | */
|
1096 | readonly freeSockets: NodeJS.ReadOnlyDict<Socket[]>;
|
1097 | /**
|
1098 | * An object which contains arrays of sockets currently in use by the
|
1099 | * agent. Do not modify.
|
1100 | * @since v0.3.6
|
1101 | */
|
1102 | readonly sockets: NodeJS.ReadOnlyDict<Socket[]>;
|
1103 | /**
|
1104 | * An object which contains queues of requests that have not yet been assigned to
|
1105 | * sockets. Do not modify.
|
1106 | * @since v0.5.9
|
1107 | */
|
1108 | readonly requests: NodeJS.ReadOnlyDict<IncomingMessage[]>;
|
1109 | constructor(opts?: AgentOptions);
|
1110 | /**
|
1111 | * Destroy any sockets that are currently in use by the agent.
|
1112 | *
|
1113 | * It is usually not necessary to do this. However, if using an
|
1114 | * agent with `keepAlive` enabled, then it is best to explicitly shut down
|
1115 | * the agent when it is no longer needed. Otherwise,
|
1116 | * sockets might stay open for quite a long time before the server
|
1117 | * terminates them.
|
1118 | * @since v0.11.4
|
1119 | */
|
1120 | destroy(): void;
|
1121 | }
|
1122 | const METHODS: string[];
|
1123 | const STATUS_CODES: {
|
1124 | [errorCode: number]: string | undefined;
|
1125 | [errorCode: string]: string | undefined;
|
1126 | };
|
1127 | /**
|
1128 | * Returns a new instance of {@link Server}.
|
1129 | *
|
1130 | * The `requestListener` is a function which is automatically
|
1131 | * added to the `'request'` event.
|
1132 | * @since v0.1.13
|
1133 | */
|
1134 | function createServer(requestListener?: RequestListener): Server;
|
1135 | function createServer(options: ServerOptions, requestListener?: RequestListener): Server;
|
1136 | // although RequestOptions are passed as ClientRequestArgs to ClientRequest directly,
|
1137 | // create interface RequestOptions would make the naming more clear to developers
|
1138 | interface RequestOptions extends ClientRequestArgs {}
|
1139 | /**
|
1140 | * Node.js maintains several connections per server to make HTTP requests.
|
1141 | * This function allows one to transparently issue requests.
|
1142 | *
|
1143 | * `url` can be a string or a `URL` object. If `url` is a
|
1144 | * string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object.
|
1145 | *
|
1146 | * If both `url` and `options` are specified, the objects are merged, with the`options` properties taking precedence.
|
1147 | *
|
1148 | * The optional `callback` parameter will be added as a one-time listener for
|
1149 | * the `'response'` event.
|
1150 | *
|
1151 | * `http.request()` returns an instance of the {@link ClientRequest} class. The `ClientRequest` instance is a writable stream. If one needs to
|
1152 | * upload a file with a POST request, then write to the `ClientRequest` object.
|
1153 | *
|
1154 | * ```js
|
1155 | * const http = require('http');
|
1156 | *
|
1157 | * const postData = JSON.stringify({
|
1158 | * 'msg': 'Hello World!'
|
1159 | * });
|
1160 | *
|
1161 | * const options = {
|
1162 | * hostname: 'www.google.com',
|
1163 | * port: 80,
|
1164 | * path: '/upload',
|
1165 | * method: 'POST',
|
1166 | * headers: {
|
1167 | * 'Content-Type': 'application/json',
|
1168 | * 'Content-Length': Buffer.byteLength(postData)
|
1169 | * }
|
1170 | * };
|
1171 | *
|
1172 | * const req = http.request(options, (res) => {
|
1173 | * console.log(`STATUS: ${res.statusCode}`);
|
1174 | * console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
|
1175 | * res.setEncoding('utf8');
|
1176 | * res.on('data', (chunk) => {
|
1177 | * console.log(`BODY: ${chunk}`);
|
1178 | * });
|
1179 | * res.on('end', () => {
|
1180 | * console.log('No more data in response.');
|
1181 | * });
|
1182 | * });
|
1183 | *
|
1184 | * req.on('error', (e) => {
|
1185 | * console.error(`problem with request: ${e.message}`);
|
1186 | * });
|
1187 | *
|
1188 | *
|
1189 | * req.write(postData);
|
1190 | * req.end();
|
1191 | * ```
|
1192 | *
|
1193 | * In the example `req.end()` was called. With `http.request()` one
|
1194 | * must always call `req.end()` to signify the end of the request -
|
1195 | * even if there is no data being written to the request body.
|
1196 | *
|
1197 | * If any error is encountered during the request (be that with DNS resolution,
|
1198 | * TCP level errors, or actual HTTP parse errors) an `'error'` event is emitted
|
1199 | * on the returned request object. As with all `'error'` events, if no listeners
|
1200 | * are registered the error will be thrown.
|
1201 | *
|
1202 | * There are a few special headers that should be noted.
|
1203 | *
|
1204 | * * Sending a 'Connection: keep-alive' will notify Node.js that the connection to
|
1205 | * the server should be persisted until the next request.
|
1206 | * * Sending a 'Content-Length' header will disable the default chunked encoding.
|
1207 | * * Sending an 'Expect' header will immediately send the request headers.
|
1208 | * Usually, when sending 'Expect: 100-continue', both a timeout and a listener
|
1209 | * for the `'continue'` event should be set. See RFC 2616 Section 8.2.3 for more
|
1210 | * information.
|
1211 | * * Sending an Authorization header will override using the `auth` option
|
1212 | * to compute basic authentication.
|
1213 | *
|
1214 | * Example using a `URL` as `options`:
|
1215 | *
|
1216 | * ```js
|
1217 | * const options = new URL('http://abc:xyz@example.com');
|
1218 | *
|
1219 | * const req = http.request(options, (res) => {
|
1220 | *
|
1221 | * });
|
1222 | * ```
|
1223 | *
|
1224 | * In a successful request, the following events will be emitted in the following
|
1225 | * order:
|
1226 | *
|
1227 | * * `'socket'`
|
1228 | * * `'response'`
|
1229 | * * `'data'` any number of times, on the `res` object
|
1230 | * (`'data'` will not be emitted at all if the response body is empty, for
|
1231 | * instance, in most redirects)
|
1232 | * * `'end'` on the `res` object
|
1233 | * * `'close'`
|
1234 | *
|
1235 | * In the case of a connection error, the following events will be emitted:
|
1236 | *
|
1237 | * * `'socket'`
|
1238 | * * `'error'`
|
1239 | * * `'close'`
|
1240 | *
|
1241 | * In the case of a premature connection close before the response is received,
|
1242 | * the following events will be emitted in the following order:
|
1243 | *
|
1244 | * * `'socket'`
|
1245 | * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'`
|
1246 | * * `'close'`
|
1247 | *
|
1248 | * In the case of a premature connection close after the response is received,
|
1249 | * the following events will be emitted in the following order:
|
1250 | *
|
1251 | * * `'socket'`
|
1252 | * * `'response'`
|
1253 | * * `'data'` any number of times, on the `res` object
|
1254 | * * (connection closed here)
|
1255 | * * `'aborted'` on the `res` object
|
1256 | * * `'error'` on the `res` object with an error with message`'Error: aborted'` and code `'ECONNRESET'`.
|
1257 | * * `'close'`
|
1258 | * * `'close'` on the `res` object
|
1259 | *
|
1260 | * If `req.destroy()` is called before a socket is assigned, the following
|
1261 | * events will be emitted in the following order:
|
1262 | *
|
1263 | * * (`req.destroy()` called here)
|
1264 | * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'`
|
1265 | * * `'close'`
|
1266 | *
|
1267 | * If `req.destroy()` is called before the connection succeeds, the following
|
1268 | * events will be emitted in the following order:
|
1269 | *
|
1270 | * * `'socket'`
|
1271 | * * (`req.destroy()` called here)
|
1272 | * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'`
|
1273 | * * `'close'`
|
1274 | *
|
1275 | * If `req.destroy()` is called after the response is received, the following
|
1276 | * events will be emitted in the following order:
|
1277 | *
|
1278 | * * `'socket'`
|
1279 | * * `'response'`
|
1280 | * * `'data'` any number of times, on the `res` object
|
1281 | * * (`req.destroy()` called here)
|
1282 | * * `'aborted'` on the `res` object
|
1283 | * * `'error'` on the `res` object with an error with message`'Error: aborted'` and code `'ECONNRESET'`.
|
1284 | * * `'close'`
|
1285 | * * `'close'` on the `res` object
|
1286 | *
|
1287 | * If `req.abort()` is called before a socket is assigned, the following
|
1288 | * events will be emitted in the following order:
|
1289 | *
|
1290 | * * (`req.abort()` called here)
|
1291 | * * `'abort'`
|
1292 | * * `'close'`
|
1293 | *
|
1294 | * If `req.abort()` is called before the connection succeeds, the following
|
1295 | * events will be emitted in the following order:
|
1296 | *
|
1297 | * * `'socket'`
|
1298 | * * (`req.abort()` called here)
|
1299 | * * `'abort'`
|
1300 | * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'`
|
1301 | * * `'close'`
|
1302 | *
|
1303 | * If `req.abort()` is called after the response is received, the following
|
1304 | * events will be emitted in the following order:
|
1305 | *
|
1306 | * * `'socket'`
|
1307 | * * `'response'`
|
1308 | * * `'data'` any number of times, on the `res` object
|
1309 | * * (`req.abort()` called here)
|
1310 | * * `'abort'`
|
1311 | * * `'aborted'` on the `res` object
|
1312 | * * `'error'` on the `res` object with an error with message`'Error: aborted'` and code `'ECONNRESET'`.
|
1313 | * * `'close'`
|
1314 | * * `'close'` on the `res` object
|
1315 | *
|
1316 | * Setting the `timeout` option or using the `setTimeout()` function will
|
1317 | * not abort the request or do anything besides add a `'timeout'` event.
|
1318 | *
|
1319 | * Passing an `AbortSignal` and then calling `abort` on the corresponding`AbortController` will behave the same way as calling `.destroy()` on the
|
1320 | * request itself.
|
1321 | * @since v0.3.6
|
1322 | */
|
1323 | function request(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest;
|
1324 | function request(url: string | URL, options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest;
|
1325 | /**
|
1326 | * Since most requests are GET requests without bodies, Node.js provides this
|
1327 | * 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
|
1328 | * response
|
1329 | * data for reasons stated in {@link ClientRequest} section.
|
1330 | *
|
1331 | * The `callback` is invoked with a single argument that is an instance of {@link IncomingMessage}.
|
1332 | *
|
1333 | * JSON fetching example:
|
1334 | *
|
1335 | * ```js
|
1336 | * http.get('http://localhost:8000/', (res) => {
|
1337 | * const { statusCode } = res;
|
1338 | * const contentType = res.headers['content-type'];
|
1339 | *
|
1340 | * let error;
|
1341 | *
|
1342 | *
|
1343 | * if (statusCode !== 200) {
|
1344 | * error = new Error('Request Failed.\n' +
|
1345 | * `Status Code: ${statusCode}`);
|
1346 | * } else if (!/^application\/json/.test(contentType)) {
|
1347 | * error = new Error('Invalid content-type.\n' +
|
1348 | * `Expected application/json but received ${contentType}`);
|
1349 | * }
|
1350 | * if (error) {
|
1351 | * console.error(error.message);
|
1352 | *
|
1353 | * res.resume();
|
1354 | * return;
|
1355 | * }
|
1356 | *
|
1357 | * res.setEncoding('utf8');
|
1358 | * let rawData = '';
|
1359 | * res.on('data', (chunk) => { rawData += chunk; });
|
1360 | * res.on('end', () => {
|
1361 | * try {
|
1362 | * const parsedData = JSON.parse(rawData);
|
1363 | * console.log(parsedData);
|
1364 | * } catch (e) {
|
1365 | * console.error(e.message);
|
1366 | * }
|
1367 | * });
|
1368 | * }).on('error', (e) => {
|
1369 | * console.error(`Got error: ${e.message}`);
|
1370 | * });
|
1371 | *
|
1372 | *
|
1373 | * const server = http.createServer((req, res) => {
|
1374 | * res.writeHead(200, { 'Content-Type': 'application/json' });
|
1375 | * res.end(JSON.stringify({
|
1376 | * data: 'Hello World!'
|
1377 | * }));
|
1378 | * });
|
1379 | *
|
1380 | * server.listen(8000);
|
1381 | * ```
|
1382 | * @since v0.3.6
|
1383 | * @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.
|
1384 | */
|
1385 | function get(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest;
|
1386 | function get(url: string | URL, options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest;
|
1387 | let globalAgent: Agent;
|
1388 | /**
|
1389 | * Read-only property specifying the maximum allowed size of HTTP headers in bytes.
|
1390 | * Defaults to 16KB. Configurable using the `--max-http-header-size` CLI option.
|
1391 | */
|
1392 | const maxHeaderSize: number;
|
1393 | }
|
1394 | declare module 'node:http' {
|
1395 | export * from 'http';
|
1396 | }
|
1397 |
|
\ | No newline at end of file |