6ee4ac89e1efdd61cb4d57fe082c510b630376f5b27837678714ffd05a4254cee8616e5be386b2db89d2bbd65541eaa0ecebf11ebbac524a0e0b80c09bad52 86 KB

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