a1d17198097d4ebd1e32d4c7da07a97fdd5b0745ea2376ea4e9d6132fb597ad22410b3f3e2d2d4fbdd1fd0684ffa9eb766afe49c61966c68e096f6634108d3 90 KB

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