006f5b14882cacfdfafa9b7bfabd2459eba1d5a364fa36c88f35d60c5499a3f6d7b2cebf8cefbf5eb575c44543a94f5ba9ee650c8310c17b2b981ec236bf4c 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549
  1. /**
  2. * The `node:child_process` module provides the ability to spawn subprocesses in
  3. * a manner that is similar, but not identical, to [`popen(3)`](http://man7.org/linux/man-pages/man3/popen.3.html). This capability
  4. * is primarily provided by the {@link spawn} function:
  5. *
  6. * ```js
  7. * import { spawn } from 'node:child_process';
  8. * const ls = spawn('ls', ['-lh', '/usr']);
  9. *
  10. * ls.stdout.on('data', (data) => {
  11. * console.log(`stdout: ${data}`);
  12. * });
  13. *
  14. * ls.stderr.on('data', (data) => {
  15. * console.error(`stderr: ${data}`);
  16. * });
  17. *
  18. * ls.on('close', (code) => {
  19. * console.log(`child process exited with code ${code}`);
  20. * });
  21. * ```
  22. *
  23. * By default, pipes for `stdin`, `stdout`, and `stderr` are established between
  24. * the parent Node.js process and the spawned subprocess. These pipes have
  25. * limited (and platform-specific) capacity. If the subprocess writes to
  26. * stdout in excess of that limit without the output being captured, the
  27. * subprocess blocks waiting for the pipe buffer to accept more data. This is
  28. * identical to the behavior of pipes in the shell. Use the `{ stdio: 'ignore' }` option if the output will not be consumed.
  29. *
  30. * The command lookup is performed using the `options.env.PATH` environment
  31. * variable if `env` is in the `options` object. Otherwise, `process.env.PATH` is
  32. * used. If `options.env` is set without `PATH`, lookup on Unix is performed
  33. * on a default search path search of `/usr/bin:/bin` (see your operating system's
  34. * manual for execvpe/execvp), on Windows the current processes environment
  35. * variable `PATH` is used.
  36. *
  37. * On Windows, environment variables are case-insensitive. Node.js
  38. * lexicographically sorts the `env` keys and uses the first one that
  39. * case-insensitively matches. Only first (in lexicographic order) entry will be
  40. * passed to the subprocess. This might lead to issues on Windows when passing
  41. * objects to the `env` option that have multiple variants of the same key, such as `PATH` and `Path`.
  42. *
  43. * The {@link spawn} method spawns the child process asynchronously,
  44. * without blocking the Node.js event loop. The {@link spawnSync} function provides equivalent functionality in a synchronous manner that blocks
  45. * the event loop until the spawned process either exits or is terminated.
  46. *
  47. * For convenience, the `node:child_process` module provides a handful of
  48. * synchronous and asynchronous alternatives to {@link spawn} and {@link spawnSync}. Each of these alternatives are implemented on
  49. * top of {@link spawn} or {@link spawnSync}.
  50. *
  51. * * {@link exec}: spawns a shell and runs a command within that
  52. * shell, passing the `stdout` and `stderr` to a callback function when
  53. * complete.
  54. * * {@link execFile}: similar to {@link exec} except
  55. * that it spawns the command directly without first spawning a shell by
  56. * default.
  57. * * {@link fork}: spawns a new Node.js process and invokes a
  58. * specified module with an IPC communication channel established that allows
  59. * sending messages between parent and child.
  60. * * {@link execSync}: a synchronous version of {@link exec} that will block the Node.js event loop.
  61. * * {@link execFileSync}: a synchronous version of {@link execFile} that will block the Node.js event loop.
  62. *
  63. * For certain use cases, such as automating shell scripts, the `synchronous counterparts` may be more convenient. In many cases, however,
  64. * the synchronous methods can have significant impact on performance due to
  65. * stalling the event loop while spawned processes complete.
  66. * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/child_process.js)
  67. */
  68. declare module "child_process" {
  69. import { ObjectEncodingOptions } from "node:fs";
  70. import { Abortable, EventEmitter } from "node:events";
  71. import * as dgram from "node:dgram";
  72. import * as net from "node:net";
  73. import { Pipe, Readable, Stream, Writable } from "node:stream";
  74. import { URL } from "node:url";
  75. type Serializable = string | object | number | boolean | bigint;
  76. type SendHandle = net.Socket | net.Server | dgram.Socket | undefined;
  77. /**
  78. * Instances of the `ChildProcess` represent spawned child processes.
  79. *
  80. * Instances of `ChildProcess` are not intended to be created directly. Rather,
  81. * use the {@link spawn}, {@link exec},{@link execFile}, or {@link fork} methods to create
  82. * instances of `ChildProcess`.
  83. * @since v2.2.0
  84. */
  85. class ChildProcess extends EventEmitter {
  86. /**
  87. * A `Writable Stream` that represents the child process's `stdin`.
  88. *
  89. * If a child process waits to read all of its input, the child will not continue
  90. * until this stream has been closed via `end()`.
  91. *
  92. * If the child was spawned with `stdio[0]` set to anything other than `'pipe'`,
  93. * then this will be `null`.
  94. *
  95. * `subprocess.stdin` is an alias for `subprocess.stdio[0]`. Both properties will
  96. * refer to the same value.
  97. *
  98. * The `subprocess.stdin` property can be `null` or `undefined` if the child process could not be successfully spawned.
  99. * @since v0.1.90
  100. */
  101. stdin: Writable | null;
  102. /**
  103. * A `Readable Stream` that represents the child process's `stdout`.
  104. *
  105. * If the child was spawned with `stdio[1]` set to anything other than `'pipe'`,
  106. * then this will be `null`.
  107. *
  108. * `subprocess.stdout` is an alias for `subprocess.stdio[1]`. Both properties will
  109. * refer to the same value.
  110. *
  111. * ```js
  112. * import { spawn } from 'node:child_process';
  113. *
  114. * const subprocess = spawn('ls');
  115. *
  116. * subprocess.stdout.on('data', (data) => {
  117. * console.log(`Received chunk ${data}`);
  118. * });
  119. * ```
  120. *
  121. * The `subprocess.stdout` property can be `null` or `undefined` if the child process could not be successfully spawned.
  122. * @since v0.1.90
  123. */
  124. stdout: Readable | null;
  125. /**
  126. * A `Readable Stream` that represents the child process's `stderr`.
  127. *
  128. * If the child was spawned with `stdio[2]` set to anything other than `'pipe'`,
  129. * then this will be `null`.
  130. *
  131. * `subprocess.stderr` is an alias for `subprocess.stdio[2]`. Both properties will
  132. * refer to the same value.
  133. *
  134. * The `subprocess.stderr` property can be `null` or `undefined` if the child process could not be successfully spawned.
  135. * @since v0.1.90
  136. */
  137. stderr: Readable | null;
  138. /**
  139. * The `subprocess.channel` property is a reference to the child's IPC channel. If
  140. * no IPC channel exists, this property is `undefined`.
  141. * @since v7.1.0
  142. */
  143. readonly channel?: Pipe | null | undefined;
  144. /**
  145. * A sparse array of pipes to the child process, corresponding with positions in
  146. * the `stdio` option passed to {@link spawn} that have been set
  147. * to the value `'pipe'`. `subprocess.stdio[0]`, `subprocess.stdio[1]`, and `subprocess.stdio[2]` are also available as `subprocess.stdin`, `subprocess.stdout`, and `subprocess.stderr`,
  148. * respectively.
  149. *
  150. * In the following example, only the child's fd `1` (stdout) is configured as a
  151. * pipe, so only the parent's `subprocess.stdio[1]` is a stream, all other values
  152. * in the array are `null`.
  153. *
  154. * ```js
  155. * import assert from 'node:assert';
  156. * import fs from 'node:fs';
  157. * import child_process from 'node:child_process';
  158. *
  159. * const subprocess = child_process.spawn('ls', {
  160. * stdio: [
  161. * 0, // Use parent's stdin for child.
  162. * 'pipe', // Pipe child's stdout to parent.
  163. * fs.openSync('err.out', 'w'), // Direct child's stderr to a file.
  164. * ],
  165. * });
  166. *
  167. * assert.strictEqual(subprocess.stdio[0], null);
  168. * assert.strictEqual(subprocess.stdio[0], subprocess.stdin);
  169. *
  170. * assert(subprocess.stdout);
  171. * assert.strictEqual(subprocess.stdio[1], subprocess.stdout);
  172. *
  173. * assert.strictEqual(subprocess.stdio[2], null);
  174. * assert.strictEqual(subprocess.stdio[2], subprocess.stderr);
  175. * ```
  176. *
  177. * The `subprocess.stdio` property can be `undefined` if the child process could
  178. * not be successfully spawned.
  179. * @since v0.7.10
  180. */
  181. readonly stdio: [
  182. Writable | null,
  183. // stdin
  184. Readable | null,
  185. // stdout
  186. Readable | null,
  187. // stderr
  188. Readable | Writable | null | undefined,
  189. // extra
  190. Readable | Writable | null | undefined, // extra
  191. ];
  192. /**
  193. * The `subprocess.killed` property indicates whether the child process
  194. * successfully received a signal from `subprocess.kill()`. The `killed` property
  195. * does not indicate that the child process has been terminated.
  196. * @since v0.5.10
  197. */
  198. readonly killed: boolean;
  199. /**
  200. * Returns the process identifier (PID) of the child process. If the child process
  201. * fails to spawn due to errors, then the value is `undefined` and `error` is
  202. * emitted.
  203. *
  204. * ```js
  205. * import { spawn } from 'node:child_process';
  206. * const grep = spawn('grep', ['ssh']);
  207. *
  208. * console.log(`Spawned child pid: ${grep.pid}`);
  209. * grep.stdin.end();
  210. * ```
  211. * @since v0.1.90
  212. */
  213. readonly pid?: number | undefined;
  214. /**
  215. * The `subprocess.connected` property indicates whether it is still possible to
  216. * send and receive messages from a child process. When `subprocess.connected` is `false`, it is no longer possible to send or receive messages.
  217. * @since v0.7.2
  218. */
  219. readonly connected: boolean;
  220. /**
  221. * The `subprocess.exitCode` property indicates the exit code of the child process.
  222. * If the child process is still running, the field will be `null`.
  223. */
  224. readonly exitCode: number | null;
  225. /**
  226. * The `subprocess.signalCode` property indicates the signal received by
  227. * the child process if any, else `null`.
  228. */
  229. readonly signalCode: NodeJS.Signals | null;
  230. /**
  231. * The `subprocess.spawnargs` property represents the full list of command-line
  232. * arguments the child process was launched with.
  233. */
  234. readonly spawnargs: string[];
  235. /**
  236. * The `subprocess.spawnfile` property indicates the executable file name of
  237. * the child process that is launched.
  238. *
  239. * For {@link fork}, its value will be equal to `process.execPath`.
  240. * For {@link spawn}, its value will be the name of
  241. * the executable file.
  242. * For {@link exec}, its value will be the name of the shell
  243. * in which the child process is launched.
  244. */
  245. readonly spawnfile: string;
  246. /**
  247. * The `subprocess.kill()` method sends a signal to the child process. If no
  248. * argument is given, the process will be sent the `'SIGTERM'` signal. See [`signal(7)`](http://man7.org/linux/man-pages/man7/signal.7.html) for a list of available signals. This function
  249. * returns `true` if [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) succeeds, and `false` otherwise.
  250. *
  251. * ```js
  252. * import { spawn } from 'node:child_process';
  253. * const grep = spawn('grep', ['ssh']);
  254. *
  255. * grep.on('close', (code, signal) => {
  256. * console.log(
  257. * `child process terminated due to receipt of signal ${signal}`);
  258. * });
  259. *
  260. * // Send SIGHUP to process.
  261. * grep.kill('SIGHUP');
  262. * ```
  263. *
  264. * The `ChildProcess` object may emit an `'error'` event if the signal
  265. * cannot be delivered. Sending a signal to a child process that has already exited
  266. * is not an error but may have unforeseen consequences. Specifically, if the
  267. * process identifier (PID) has been reassigned to another process, the signal will
  268. * be delivered to that process instead which can have unexpected results.
  269. *
  270. * While the function is called `kill`, the signal delivered to the child process
  271. * may not actually terminate the process.
  272. *
  273. * See [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) for reference.
  274. *
  275. * On Windows, where POSIX signals do not exist, the `signal` argument will be
  276. * ignored, and the process will be killed forcefully and abruptly (similar to `'SIGKILL'`).
  277. * See `Signal Events` for more details.
  278. *
  279. * On Linux, child processes of child processes will not be terminated
  280. * when attempting to kill their parent. This is likely to happen when running a
  281. * new process in a shell or with the use of the `shell` option of `ChildProcess`:
  282. *
  283. * ```js
  284. * 'use strict';
  285. * import { spawn } from 'node:child_process';
  286. *
  287. * const subprocess = spawn(
  288. * 'sh',
  289. * [
  290. * '-c',
  291. * `node -e "setInterval(() => {
  292. * console.log(process.pid, 'is alive')
  293. * }, 500);"`,
  294. * ], {
  295. * stdio: ['inherit', 'inherit', 'inherit'],
  296. * },
  297. * );
  298. *
  299. * setTimeout(() => {
  300. * subprocess.kill(); // Does not terminate the Node.js process in the shell.
  301. * }, 2000);
  302. * ```
  303. * @since v0.1.90
  304. */
  305. kill(signal?: NodeJS.Signals | number): boolean;
  306. /**
  307. * Calls {@link ChildProcess.kill} with `'SIGTERM'`.
  308. * @since v20.5.0
  309. */
  310. [Symbol.dispose](): void;
  311. /**
  312. * When an IPC channel has been established between the parent and child (
  313. * i.e. when using {@link fork}), the `subprocess.send()` method can
  314. * be used to send messages to the child process. When the child process is a
  315. * Node.js instance, these messages can be received via the `'message'` event.
  316. *
  317. * The message goes through serialization and parsing. The resulting
  318. * message might not be the same as what is originally sent.
  319. *
  320. * For example, in the parent script:
  321. *
  322. * ```js
  323. * import cp from 'node:child_process';
  324. * const n = cp.fork(`${__dirname}/sub.js`);
  325. *
  326. * n.on('message', (m) => {
  327. * console.log('PARENT got message:', m);
  328. * });
  329. *
  330. * // Causes the child to print: CHILD got message: { hello: 'world' }
  331. * n.send({ hello: 'world' });
  332. * ```
  333. *
  334. * And then the child script, `'sub.js'` might look like this:
  335. *
  336. * ```js
  337. * process.on('message', (m) => {
  338. * console.log('CHILD got message:', m);
  339. * });
  340. *
  341. * // Causes the parent to print: PARENT got message: { foo: 'bar', baz: null }
  342. * process.send({ foo: 'bar', baz: NaN });
  343. * ```
  344. *
  345. * Child Node.js processes will have a `process.send()` method of their own
  346. * that allows the child to send messages back to the parent.
  347. *
  348. * There is a special case when sending a `{cmd: 'NODE_foo'}` message. Messages
  349. * containing a `NODE_` prefix in the `cmd` property are reserved for use within
  350. * Node.js core and will not be emitted in the child's `'message'` event. Rather, such messages are emitted using the `'internalMessage'` event and are consumed internally by Node.js.
  351. * Applications should avoid using such messages or listening for `'internalMessage'` events as it is subject to change without notice.
  352. *
  353. * The optional `sendHandle` argument that may be passed to `subprocess.send()` is
  354. * for passing a TCP server or socket object to the child process. The child will
  355. * receive the object as the second argument passed to the callback function
  356. * registered on the `'message'` event. Any data that is received and buffered in
  357. * the socket will not be sent to the child. Sending IPC sockets is not supported on Windows.
  358. *
  359. * The optional `callback` is a function that is invoked after the message is
  360. * sent but before the child may have received it. The function is called with a
  361. * single argument: `null` on success, or an `Error` object on failure.
  362. *
  363. * If no `callback` function is provided and the message cannot be sent, an `'error'` event will be emitted by the `ChildProcess` object. This can
  364. * happen, for instance, when the child process has already exited.
  365. *
  366. * `subprocess.send()` will return `false` if the channel has closed or when the
  367. * backlog of unsent messages exceeds a threshold that makes it unwise to send
  368. * more. Otherwise, the method returns `true`. The `callback` function can be
  369. * used to implement flow control.
  370. *
  371. * #### Example: sending a server object
  372. *
  373. * The `sendHandle` argument can be used, for instance, to pass the handle of
  374. * a TCP server object to the child process as illustrated in the example below:
  375. *
  376. * ```js
  377. * import { createServer } from 'node:net';
  378. * import { fork } from 'node:child_process';
  379. * const subprocess = fork('subprocess.js');
  380. *
  381. * // Open up the server object and send the handle.
  382. * const server = createServer();
  383. * server.on('connection', (socket) => {
  384. * socket.end('handled by parent');
  385. * });
  386. * server.listen(1337, () => {
  387. * subprocess.send('server', server);
  388. * });
  389. * ```
  390. *
  391. * The child would then receive the server object as:
  392. *
  393. * ```js
  394. * process.on('message', (m, server) => {
  395. * if (m === 'server') {
  396. * server.on('connection', (socket) => {
  397. * socket.end('handled by child');
  398. * });
  399. * }
  400. * });
  401. * ```
  402. *
  403. * Once the server is now shared between the parent and child, some connections
  404. * can be handled by the parent and some by the child.
  405. *
  406. * While the example above uses a server created using the `node:net` module, `node:dgram` module servers use exactly the same workflow with the exceptions of
  407. * listening on a `'message'` event instead of `'connection'` and using `server.bind()` instead of `server.listen()`. This is, however, only
  408. * supported on Unix platforms.
  409. *
  410. * #### Example: sending a socket object
  411. *
  412. * Similarly, the `sendHandler` argument can be used to pass the handle of a
  413. * socket to the child process. The example below spawns two children that each
  414. * handle connections with "normal" or "special" priority:
  415. *
  416. * ```js
  417. * import { createServer } from 'node:net';
  418. * import { fork } from 'node:child_process';
  419. * const normal = fork('subprocess.js', ['normal']);
  420. * const special = fork('subprocess.js', ['special']);
  421. *
  422. * // Open up the server and send sockets to child. Use pauseOnConnect to prevent
  423. * // the sockets from being read before they are sent to the child process.
  424. * const server = createServer({ pauseOnConnect: true });
  425. * server.on('connection', (socket) => {
  426. *
  427. * // If this is special priority...
  428. * if (socket.remoteAddress === '74.125.127.100') {
  429. * special.send('socket', socket);
  430. * return;
  431. * }
  432. * // This is normal priority.
  433. * normal.send('socket', socket);
  434. * });
  435. * server.listen(1337);
  436. * ```
  437. *
  438. * The `subprocess.js` would receive the socket handle as the second argument
  439. * passed to the event callback function:
  440. *
  441. * ```js
  442. * process.on('message', (m, socket) => {
  443. * if (m === 'socket') {
  444. * if (socket) {
  445. * // Check that the client socket exists.
  446. * // It is possible for the socket to be closed between the time it is
  447. * // sent and the time it is received in the child process.
  448. * socket.end(`Request handled with ${process.argv[2]} priority`);
  449. * }
  450. * }
  451. * });
  452. * ```
  453. *
  454. * Do not use `.maxConnections` on a socket that has been passed to a subprocess.
  455. * The parent cannot track when the socket is destroyed.
  456. *
  457. * Any `'message'` handlers in the subprocess should verify that `socket` exists,
  458. * as the connection may have been closed during the time it takes to send the
  459. * connection to the child.
  460. * @since v0.5.9
  461. * @param sendHandle `undefined`, or a [`net.Socket`](https://nodejs.org/docs/latest-v22.x/api/net.html#class-netsocket), [`net.Server`](https://nodejs.org/docs/latest-v22.x/api/net.html#class-netserver), or [`dgram.Socket`](https://nodejs.org/docs/latest-v22.x/api/dgram.html#class-dgramsocket) object.
  462. * @param options The `options` argument, if present, is an object used to parameterize the sending of certain types of handles. `options` supports the following properties:
  463. */
  464. send(message: Serializable, callback?: (error: Error | null) => void): boolean;
  465. send(message: Serializable, sendHandle?: SendHandle, callback?: (error: Error | null) => void): boolean;
  466. send(
  467. message: Serializable,
  468. sendHandle?: SendHandle,
  469. options?: MessageOptions,
  470. callback?: (error: Error | null) => void,
  471. ): boolean;
  472. /**
  473. * Closes the IPC channel between parent and child, allowing the child to exit
  474. * gracefully once there are no other connections keeping it alive. After calling
  475. * this method the `subprocess.connected` and `process.connected` properties in
  476. * both the parent and child (respectively) will be set to `false`, and it will be
  477. * no longer possible to pass messages between the processes.
  478. *
  479. * The `'disconnect'` event will be emitted when there are no messages in the
  480. * process of being received. This will most often be triggered immediately after
  481. * calling `subprocess.disconnect()`.
  482. *
  483. * When the child process is a Node.js instance (e.g. spawned using {@link fork}), the `process.disconnect()` method can be invoked
  484. * within the child process to close the IPC channel as well.
  485. * @since v0.7.2
  486. */
  487. disconnect(): void;
  488. /**
  489. * By default, the parent will wait for the detached child to exit. To prevent the
  490. * parent from waiting for a given `subprocess` to exit, use the `subprocess.unref()` method. Doing so will cause the parent's event loop to not
  491. * include the child in its reference count, allowing the parent to exit
  492. * independently of the child, unless there is an established IPC channel between
  493. * the child and the parent.
  494. *
  495. * ```js
  496. * import { spawn } from 'node:child_process';
  497. *
  498. * const subprocess = spawn(process.argv[0], ['child_program.js'], {
  499. * detached: true,
  500. * stdio: 'ignore',
  501. * });
  502. *
  503. * subprocess.unref();
  504. * ```
  505. * @since v0.7.10
  506. */
  507. unref(): void;
  508. /**
  509. * Calling `subprocess.ref()` after making a call to `subprocess.unref()` will
  510. * restore the removed reference count for the child process, forcing the parent
  511. * to wait for the child to exit before exiting itself.
  512. *
  513. * ```js
  514. * import { spawn } from 'node:child_process';
  515. *
  516. * const subprocess = spawn(process.argv[0], ['child_program.js'], {
  517. * detached: true,
  518. * stdio: 'ignore',
  519. * });
  520. *
  521. * subprocess.unref();
  522. * subprocess.ref();
  523. * ```
  524. * @since v0.7.10
  525. */
  526. ref(): void;
  527. /**
  528. * events.EventEmitter
  529. * 1. close
  530. * 2. disconnect
  531. * 3. error
  532. * 4. exit
  533. * 5. message
  534. * 6. spawn
  535. */
  536. addListener(event: string, listener: (...args: any[]) => void): this;
  537. addListener(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this;
  538. addListener(event: "disconnect", listener: () => void): this;
  539. addListener(event: "error", listener: (err: Error) => void): this;
  540. addListener(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this;
  541. addListener(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this;
  542. addListener(event: "spawn", listener: () => void): this;
  543. emit(event: string | symbol, ...args: any[]): boolean;
  544. emit(event: "close", code: number | null, signal: NodeJS.Signals | null): boolean;
  545. emit(event: "disconnect"): boolean;
  546. emit(event: "error", err: Error): boolean;
  547. emit(event: "exit", code: number | null, signal: NodeJS.Signals | null): boolean;
  548. emit(event: "message", message: Serializable, sendHandle: SendHandle): boolean;
  549. emit(event: "spawn", listener: () => void): boolean;
  550. on(event: string, listener: (...args: any[]) => void): this;
  551. on(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this;
  552. on(event: "disconnect", listener: () => void): this;
  553. on(event: "error", listener: (err: Error) => void): this;
  554. on(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this;
  555. on(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this;
  556. on(event: "spawn", listener: () => void): this;
  557. once(event: string, listener: (...args: any[]) => void): this;
  558. once(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this;
  559. once(event: "disconnect", listener: () => void): this;
  560. once(event: "error", listener: (err: Error) => void): this;
  561. once(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this;
  562. once(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this;
  563. once(event: "spawn", listener: () => void): this;
  564. prependListener(event: string, listener: (...args: any[]) => void): this;
  565. prependListener(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this;
  566. prependListener(event: "disconnect", listener: () => void): this;
  567. prependListener(event: "error", listener: (err: Error) => void): this;
  568. prependListener(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this;
  569. prependListener(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this;
  570. prependListener(event: "spawn", listener: () => void): this;
  571. prependOnceListener(event: string, listener: (...args: any[]) => void): this;
  572. prependOnceListener(
  573. event: "close",
  574. listener: (code: number | null, signal: NodeJS.Signals | null) => void,
  575. ): this;
  576. prependOnceListener(event: "disconnect", listener: () => void): this;
  577. prependOnceListener(event: "error", listener: (err: Error) => void): this;
  578. prependOnceListener(
  579. event: "exit",
  580. listener: (code: number | null, signal: NodeJS.Signals | null) => void,
  581. ): this;
  582. prependOnceListener(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this;
  583. prependOnceListener(event: "spawn", listener: () => void): this;
  584. }
  585. // return this object when stdio option is undefined or not specified
  586. interface ChildProcessWithoutNullStreams extends ChildProcess {
  587. stdin: Writable;
  588. stdout: Readable;
  589. stderr: Readable;
  590. readonly stdio: [
  591. Writable,
  592. Readable,
  593. Readable,
  594. // stderr
  595. Readable | Writable | null | undefined,
  596. // extra, no modification
  597. Readable | Writable | null | undefined, // extra, no modification
  598. ];
  599. }
  600. // return this object when stdio option is a tuple of 3
  601. interface ChildProcessByStdio<I extends null | Writable, O extends null | Readable, E extends null | Readable>
  602. extends ChildProcess
  603. {
  604. stdin: I;
  605. stdout: O;
  606. stderr: E;
  607. readonly stdio: [
  608. I,
  609. O,
  610. E,
  611. Readable | Writable | null | undefined,
  612. // extra, no modification
  613. Readable | Writable | null | undefined, // extra, no modification
  614. ];
  615. }
  616. interface MessageOptions {
  617. keepOpen?: boolean | undefined;
  618. }
  619. type IOType = "overlapped" | "pipe" | "ignore" | "inherit";
  620. type StdioOptions = IOType | Array<IOType | "ipc" | Stream | number | null | undefined>;
  621. type SerializationType = "json" | "advanced";
  622. interface MessagingOptions extends Abortable {
  623. /**
  624. * Specify the kind of serialization used for sending messages between processes.
  625. * @default 'json'
  626. */
  627. serialization?: SerializationType | undefined;
  628. /**
  629. * The signal value to be used when the spawned process will be killed by the abort signal.
  630. * @default 'SIGTERM'
  631. */
  632. killSignal?: NodeJS.Signals | number | undefined;
  633. /**
  634. * In milliseconds the maximum amount of time the process is allowed to run.
  635. */
  636. timeout?: number | undefined;
  637. }
  638. interface ProcessEnvOptions {
  639. uid?: number | undefined;
  640. gid?: number | undefined;
  641. cwd?: string | URL | undefined;
  642. env?: NodeJS.ProcessEnv | undefined;
  643. }
  644. interface CommonOptions extends ProcessEnvOptions {
  645. /**
  646. * @default false
  647. */
  648. windowsHide?: boolean | undefined;
  649. /**
  650. * @default 0
  651. */
  652. timeout?: number | undefined;
  653. }
  654. interface CommonSpawnOptions extends CommonOptions, MessagingOptions, Abortable {
  655. argv0?: string | undefined;
  656. /**
  657. * Can be set to 'pipe', 'inherit', 'overlapped', or 'ignore', or an array of these strings.
  658. * If passed as an array, the first element is used for `stdin`, the second for
  659. * `stdout`, and the third for `stderr`. A fourth element can be used to
  660. * specify the `stdio` behavior beyond the standard streams. See
  661. * {@link ChildProcess.stdio} for more information.
  662. *
  663. * @default 'pipe'
  664. */
  665. stdio?: StdioOptions | undefined;
  666. shell?: boolean | string | undefined;
  667. windowsVerbatimArguments?: boolean | undefined;
  668. }
  669. interface SpawnOptions extends CommonSpawnOptions {
  670. detached?: boolean | undefined;
  671. }
  672. interface SpawnOptionsWithoutStdio extends SpawnOptions {
  673. stdio?: StdioPipeNamed | StdioPipe[] | undefined;
  674. }
  675. type StdioNull = "inherit" | "ignore" | Stream;
  676. type StdioPipeNamed = "pipe" | "overlapped";
  677. type StdioPipe = undefined | null | StdioPipeNamed;
  678. interface SpawnOptionsWithStdioTuple<
  679. Stdin extends StdioNull | StdioPipe,
  680. Stdout extends StdioNull | StdioPipe,
  681. Stderr extends StdioNull | StdioPipe,
  682. > extends SpawnOptions {
  683. stdio: [Stdin, Stdout, Stderr];
  684. }
  685. /**
  686. * The `child_process.spawn()` method spawns a new process using the given `command`, with command-line arguments in `args`. If omitted, `args` defaults
  687. * to an empty array.
  688. *
  689. * **If the `shell` option is enabled, do not pass unsanitized user input to this**
  690. * **function. Any input containing shell metacharacters may be used to trigger**
  691. * **arbitrary command execution.**
  692. *
  693. * A third argument may be used to specify additional options, with these defaults:
  694. *
  695. * ```js
  696. * const defaults = {
  697. * cwd: undefined,
  698. * env: process.env,
  699. * };
  700. * ```
  701. *
  702. * Use `cwd` to specify the working directory from which the process is spawned.
  703. * If not given, the default is to inherit the current working directory. If given,
  704. * but the path does not exist, the child process emits an `ENOENT` error
  705. * and exits immediately. `ENOENT` is also emitted when the command
  706. * does not exist.
  707. *
  708. * Use `env` to specify environment variables that will be visible to the new
  709. * process, the default is `process.env`.
  710. *
  711. * `undefined` values in `env` will be ignored.
  712. *
  713. * Example of running `ls -lh /usr`, capturing `stdout`, `stderr`, and the
  714. * exit code:
  715. *
  716. * ```js
  717. * import { spawn } from 'node:child_process';
  718. * const ls = spawn('ls', ['-lh', '/usr']);
  719. *
  720. * ls.stdout.on('data', (data) => {
  721. * console.log(`stdout: ${data}`);
  722. * });
  723. *
  724. * ls.stderr.on('data', (data) => {
  725. * console.error(`stderr: ${data}`);
  726. * });
  727. *
  728. * ls.on('close', (code) => {
  729. * console.log(`child process exited with code ${code}`);
  730. * });
  731. * ```
  732. *
  733. * Example: A very elaborate way to run `ps ax | grep ssh`
  734. *
  735. * ```js
  736. * import { spawn } from 'node:child_process';
  737. * const ps = spawn('ps', ['ax']);
  738. * const grep = spawn('grep', ['ssh']);
  739. *
  740. * ps.stdout.on('data', (data) => {
  741. * grep.stdin.write(data);
  742. * });
  743. *
  744. * ps.stderr.on('data', (data) => {
  745. * console.error(`ps stderr: ${data}`);
  746. * });
  747. *
  748. * ps.on('close', (code) => {
  749. * if (code !== 0) {
  750. * console.log(`ps process exited with code ${code}`);
  751. * }
  752. * grep.stdin.end();
  753. * });
  754. *
  755. * grep.stdout.on('data', (data) => {
  756. * console.log(data.toString());
  757. * });
  758. *
  759. * grep.stderr.on('data', (data) => {
  760. * console.error(`grep stderr: ${data}`);
  761. * });
  762. *
  763. * grep.on('close', (code) => {
  764. * if (code !== 0) {
  765. * console.log(`grep process exited with code ${code}`);
  766. * }
  767. * });
  768. * ```
  769. *
  770. * Example of checking for failed `spawn`:
  771. *
  772. * ```js
  773. * import { spawn } from 'node:child_process';
  774. * const subprocess = spawn('bad_command');
  775. *
  776. * subprocess.on('error', (err) => {
  777. * console.error('Failed to start subprocess.');
  778. * });
  779. * ```
  780. *
  781. * Certain platforms (macOS, Linux) will use the value of `argv[0]` for the process
  782. * title while others (Windows, SunOS) will use `command`.
  783. *
  784. * Node.js overwrites `argv[0]` with `process.execPath` on startup, so `process.argv[0]` in a Node.js child process will not match the `argv0` parameter passed to `spawn` from the parent. Retrieve
  785. * it with the `process.argv0` property instead.
  786. *
  787. * If the `signal` option is enabled, calling `.abort()` on the corresponding `AbortController` is similar to calling `.kill()` on the child process except
  788. * the error passed to the callback will be an `AbortError`:
  789. *
  790. * ```js
  791. * import { spawn } from 'node:child_process';
  792. * const controller = new AbortController();
  793. * const { signal } = controller;
  794. * const grep = spawn('grep', ['ssh'], { signal });
  795. * grep.on('error', (err) => {
  796. * // This will be called with err being an AbortError if the controller aborts
  797. * });
  798. * controller.abort(); // Stops the child process
  799. * ```
  800. * @since v0.1.90
  801. * @param command The command to run.
  802. * @param args List of string arguments.
  803. */
  804. function spawn(command: string, options?: SpawnOptionsWithoutStdio): ChildProcessWithoutNullStreams;
  805. function spawn(
  806. command: string,
  807. options: SpawnOptionsWithStdioTuple<StdioPipe, StdioPipe, StdioPipe>,
  808. ): ChildProcessByStdio<Writable, Readable, Readable>;
  809. function spawn(
  810. command: string,
  811. options: SpawnOptionsWithStdioTuple<StdioPipe, StdioPipe, StdioNull>,
  812. ): ChildProcessByStdio<Writable, Readable, null>;
  813. function spawn(
  814. command: string,
  815. options: SpawnOptionsWithStdioTuple<StdioPipe, StdioNull, StdioPipe>,
  816. ): ChildProcessByStdio<Writable, null, Readable>;
  817. function spawn(
  818. command: string,
  819. options: SpawnOptionsWithStdioTuple<StdioNull, StdioPipe, StdioPipe>,
  820. ): ChildProcessByStdio<null, Readable, Readable>;
  821. function spawn(
  822. command: string,
  823. options: SpawnOptionsWithStdioTuple<StdioPipe, StdioNull, StdioNull>,
  824. ): ChildProcessByStdio<Writable, null, null>;
  825. function spawn(
  826. command: string,
  827. options: SpawnOptionsWithStdioTuple<StdioNull, StdioPipe, StdioNull>,
  828. ): ChildProcessByStdio<null, Readable, null>;
  829. function spawn(
  830. command: string,
  831. options: SpawnOptionsWithStdioTuple<StdioNull, StdioNull, StdioPipe>,
  832. ): ChildProcessByStdio<null, null, Readable>;
  833. function spawn(
  834. command: string,
  835. options: SpawnOptionsWithStdioTuple<StdioNull, StdioNull, StdioNull>,
  836. ): ChildProcessByStdio<null, null, null>;
  837. function spawn(command: string, options: SpawnOptions): ChildProcess;
  838. // overloads of spawn with 'args'
  839. function spawn(
  840. command: string,
  841. args?: readonly string[],
  842. options?: SpawnOptionsWithoutStdio,
  843. ): ChildProcessWithoutNullStreams;
  844. function spawn(
  845. command: string,
  846. args: readonly string[],
  847. options: SpawnOptionsWithStdioTuple<StdioPipe, StdioPipe, StdioPipe>,
  848. ): ChildProcessByStdio<Writable, Readable, Readable>;
  849. function spawn(
  850. command: string,
  851. args: readonly string[],
  852. options: SpawnOptionsWithStdioTuple<StdioPipe, StdioPipe, StdioNull>,
  853. ): ChildProcessByStdio<Writable, Readable, null>;
  854. function spawn(
  855. command: string,
  856. args: readonly string[],
  857. options: SpawnOptionsWithStdioTuple<StdioPipe, StdioNull, StdioPipe>,
  858. ): ChildProcessByStdio<Writable, null, Readable>;
  859. function spawn(
  860. command: string,
  861. args: readonly string[],
  862. options: SpawnOptionsWithStdioTuple<StdioNull, StdioPipe, StdioPipe>,
  863. ): ChildProcessByStdio<null, Readable, Readable>;
  864. function spawn(
  865. command: string,
  866. args: readonly string[],
  867. options: SpawnOptionsWithStdioTuple<StdioPipe, StdioNull, StdioNull>,
  868. ): ChildProcessByStdio<Writable, null, null>;
  869. function spawn(
  870. command: string,
  871. args: readonly string[],
  872. options: SpawnOptionsWithStdioTuple<StdioNull, StdioPipe, StdioNull>,
  873. ): ChildProcessByStdio<null, Readable, null>;
  874. function spawn(
  875. command: string,
  876. args: readonly string[],
  877. options: SpawnOptionsWithStdioTuple<StdioNull, StdioNull, StdioPipe>,
  878. ): ChildProcessByStdio<null, null, Readable>;
  879. function spawn(
  880. command: string,
  881. args: readonly string[],
  882. options: SpawnOptionsWithStdioTuple<StdioNull, StdioNull, StdioNull>,
  883. ): ChildProcessByStdio<null, null, null>;
  884. function spawn(command: string, args: readonly string[], options: SpawnOptions): ChildProcess;
  885. interface ExecOptions extends CommonOptions {
  886. shell?: string | undefined;
  887. signal?: AbortSignal | undefined;
  888. maxBuffer?: number | undefined;
  889. killSignal?: NodeJS.Signals | number | undefined;
  890. }
  891. interface ExecOptionsWithStringEncoding extends ExecOptions {
  892. encoding: BufferEncoding;
  893. }
  894. interface ExecOptionsWithBufferEncoding extends ExecOptions {
  895. encoding: BufferEncoding | null; // specify `null`.
  896. }
  897. interface ExecException extends Error {
  898. cmd?: string | undefined;
  899. killed?: boolean | undefined;
  900. code?: number | undefined;
  901. signal?: NodeJS.Signals | undefined;
  902. stdout?: string;
  903. stderr?: string;
  904. }
  905. /**
  906. * Spawns a shell then executes the `command` within that shell, buffering any
  907. * generated output. The `command` string passed to the exec function is processed
  908. * directly by the shell and special characters (vary based on [shell](https://en.wikipedia.org/wiki/List_of_command-line_interpreters))
  909. * need to be dealt with accordingly:
  910. *
  911. * ```js
  912. * import { exec } from 'node:child_process';
  913. *
  914. * exec('"/path/to/test file/test.sh" arg1 arg2');
  915. * // Double quotes are used so that the space in the path is not interpreted as
  916. * // a delimiter of multiple arguments.
  917. *
  918. * exec('echo "The \\$HOME variable is $HOME"');
  919. * // The $HOME variable is escaped in the first instance, but not in the second.
  920. * ```
  921. *
  922. * **Never pass unsanitized user input to this function. Any input containing shell**
  923. * **metacharacters may be used to trigger arbitrary command execution.**
  924. *
  925. * If a `callback` function is provided, it is called with the arguments `(error, stdout, stderr)`. On success, `error` will be `null`. On error, `error` will be an instance of `Error`. The
  926. * `error.code` property will be
  927. * the exit code of the process. By convention, any exit code other than `0` indicates an error. `error.signal` will be the signal that terminated the
  928. * process.
  929. *
  930. * The `stdout` and `stderr` arguments passed to the callback will contain the
  931. * stdout and stderr output of the child process. By default, Node.js will decode
  932. * the output as UTF-8 and pass strings to the callback. The `encoding` option
  933. * can be used to specify the character encoding used to decode the stdout and
  934. * stderr output. If `encoding` is `'buffer'`, or an unrecognized character
  935. * encoding, `Buffer` objects will be passed to the callback instead.
  936. *
  937. * ```js
  938. * import { exec } from 'node:child_process';
  939. * exec('cat *.js missing_file | wc -l', (error, stdout, stderr) => {
  940. * if (error) {
  941. * console.error(`exec error: ${error}`);
  942. * return;
  943. * }
  944. * console.log(`stdout: ${stdout}`);
  945. * console.error(`stderr: ${stderr}`);
  946. * });
  947. * ```
  948. *
  949. * If `timeout` is greater than `0`, the parent will send the signal
  950. * identified by the `killSignal` property (the default is `'SIGTERM'`) if the
  951. * child runs longer than `timeout` milliseconds.
  952. *
  953. * Unlike the [`exec(3)`](http://man7.org/linux/man-pages/man3/exec.3.html) POSIX system call, `child_process.exec()` does not replace
  954. * the existing process and uses a shell to execute the command.
  955. *
  956. * If this method is invoked as its `util.promisify()` ed version, it returns
  957. * a `Promise` for an `Object` with `stdout` and `stderr` properties. The returned `ChildProcess` instance is attached to the `Promise` as a `child` property. In
  958. * case of an error (including any error resulting in an exit code other than 0), a
  959. * rejected promise is returned, with the same `error` object given in the
  960. * callback, but with two additional properties `stdout` and `stderr`.
  961. *
  962. * ```js
  963. * import util from 'node:util';
  964. * import child_process from 'node:child_process';
  965. * const exec = util.promisify(child_process.exec);
  966. *
  967. * async function lsExample() {
  968. * const { stdout, stderr } = await exec('ls');
  969. * console.log('stdout:', stdout);
  970. * console.error('stderr:', stderr);
  971. * }
  972. * lsExample();
  973. * ```
  974. *
  975. * If the `signal` option is enabled, calling `.abort()` on the corresponding `AbortController` is similar to calling `.kill()` on the child process except
  976. * the error passed to the callback will be an `AbortError`:
  977. *
  978. * ```js
  979. * import { exec } from 'node:child_process';
  980. * const controller = new AbortController();
  981. * const { signal } = controller;
  982. * const child = exec('grep ssh', { signal }, (error) => {
  983. * console.error(error); // an AbortError
  984. * });
  985. * controller.abort();
  986. * ```
  987. * @since v0.1.90
  988. * @param command The command to run, with space-separated arguments.
  989. * @param callback called with the output when process terminates.
  990. */
  991. function exec(
  992. command: string,
  993. callback?: (error: ExecException | null, stdout: string, stderr: string) => void,
  994. ): ChildProcess;
  995. // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`.
  996. function exec(
  997. command: string,
  998. options: {
  999. encoding: "buffer" | null;
  1000. } & ExecOptions,
  1001. callback?: (error: ExecException | null, stdout: Buffer, stderr: Buffer) => void,
  1002. ): ChildProcess;
  1003. // `options` with well known `encoding` means stdout/stderr are definitely `string`.
  1004. function exec(
  1005. command: string,
  1006. options: {
  1007. encoding: BufferEncoding;
  1008. } & ExecOptions,
  1009. callback?: (error: ExecException | null, stdout: string, stderr: string) => void,
  1010. ): ChildProcess;
  1011. // `options` with an `encoding` whose type is `string` means stdout/stderr could either be `Buffer` or `string`.
  1012. // There is no guarantee the `encoding` is unknown as `string` is a superset of `BufferEncoding`.
  1013. function exec(
  1014. command: string,
  1015. options: {
  1016. encoding: BufferEncoding;
  1017. } & ExecOptions,
  1018. callback?: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void,
  1019. ): ChildProcess;
  1020. // `options` without an `encoding` means stdout/stderr are definitely `string`.
  1021. function exec(
  1022. command: string,
  1023. options: ExecOptions,
  1024. callback?: (error: ExecException | null, stdout: string, stderr: string) => void,
  1025. ): ChildProcess;
  1026. // fallback if nothing else matches. Worst case is always `string | Buffer`.
  1027. function exec(
  1028. command: string,
  1029. options: (ObjectEncodingOptions & ExecOptions) | undefined | null,
  1030. callback?: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void,
  1031. ): ChildProcess;
  1032. interface PromiseWithChild<T> extends Promise<T> {
  1033. child: ChildProcess;
  1034. }
  1035. namespace exec {
  1036. function __promisify__(command: string): PromiseWithChild<{
  1037. stdout: string;
  1038. stderr: string;
  1039. }>;
  1040. function __promisify__(
  1041. command: string,
  1042. options: {
  1043. encoding: "buffer" | null;
  1044. } & ExecOptions,
  1045. ): PromiseWithChild<{
  1046. stdout: Buffer;
  1047. stderr: Buffer;
  1048. }>;
  1049. function __promisify__(
  1050. command: string,
  1051. options: {
  1052. encoding: BufferEncoding;
  1053. } & ExecOptions,
  1054. ): PromiseWithChild<{
  1055. stdout: string;
  1056. stderr: string;
  1057. }>;
  1058. function __promisify__(
  1059. command: string,
  1060. options: ExecOptions,
  1061. ): PromiseWithChild<{
  1062. stdout: string;
  1063. stderr: string;
  1064. }>;
  1065. function __promisify__(
  1066. command: string,
  1067. options?: (ObjectEncodingOptions & ExecOptions) | null,
  1068. ): PromiseWithChild<{
  1069. stdout: string | Buffer;
  1070. stderr: string | Buffer;
  1071. }>;
  1072. }
  1073. interface ExecFileOptions extends CommonOptions, Abortable {
  1074. maxBuffer?: number | undefined;
  1075. killSignal?: NodeJS.Signals | number | undefined;
  1076. windowsVerbatimArguments?: boolean | undefined;
  1077. shell?: boolean | string | undefined;
  1078. signal?: AbortSignal | undefined;
  1079. }
  1080. interface ExecFileOptionsWithStringEncoding extends ExecFileOptions {
  1081. encoding: BufferEncoding;
  1082. }
  1083. interface ExecFileOptionsWithBufferEncoding extends ExecFileOptions {
  1084. encoding: "buffer" | null;
  1085. }
  1086. interface ExecFileOptionsWithOtherEncoding extends ExecFileOptions {
  1087. encoding: BufferEncoding;
  1088. }
  1089. type ExecFileException =
  1090. & Omit<ExecException, "code">
  1091. & Omit<NodeJS.ErrnoException, "code">
  1092. & { code?: string | number | undefined | null };
  1093. /**
  1094. * The `child_process.execFile()` function is similar to {@link exec} except that it does not spawn a shell by default. Rather, the specified
  1095. * executable `file` is spawned directly as a new process making it slightly more
  1096. * efficient than {@link exec}.
  1097. *
  1098. * The same options as {@link exec} are supported. Since a shell is
  1099. * not spawned, behaviors such as I/O redirection and file globbing are not
  1100. * supported.
  1101. *
  1102. * ```js
  1103. * import { execFile } from 'node:child_process';
  1104. * const child = execFile('node', ['--version'], (error, stdout, stderr) => {
  1105. * if (error) {
  1106. * throw error;
  1107. * }
  1108. * console.log(stdout);
  1109. * });
  1110. * ```
  1111. *
  1112. * The `stdout` and `stderr` arguments passed to the callback will contain the
  1113. * stdout and stderr output of the child process. By default, Node.js will decode
  1114. * the output as UTF-8 and pass strings to the callback. The `encoding` option
  1115. * can be used to specify the character encoding used to decode the stdout and
  1116. * stderr output. If `encoding` is `'buffer'`, or an unrecognized character
  1117. * encoding, `Buffer` objects will be passed to the callback instead.
  1118. *
  1119. * If this method is invoked as its `util.promisify()` ed version, it returns
  1120. * a `Promise` for an `Object` with `stdout` and `stderr` properties. The returned `ChildProcess` instance is attached to the `Promise` as a `child` property. In
  1121. * case of an error (including any error resulting in an exit code other than 0), a
  1122. * rejected promise is returned, with the same `error` object given in the
  1123. * callback, but with two additional properties `stdout` and `stderr`.
  1124. *
  1125. * ```js
  1126. * import util from 'node:util';
  1127. * import child_process from 'node:child_process';
  1128. * const execFile = util.promisify(child_process.execFile);
  1129. * async function getVersion() {
  1130. * const { stdout } = await execFile('node', ['--version']);
  1131. * console.log(stdout);
  1132. * }
  1133. * getVersion();
  1134. * ```
  1135. *
  1136. * **If the `shell` option is enabled, do not pass unsanitized user input to this**
  1137. * **function. Any input containing shell metacharacters may be used to trigger**
  1138. * **arbitrary command execution.**
  1139. *
  1140. * If the `signal` option is enabled, calling `.abort()` on the corresponding `AbortController` is similar to calling `.kill()` on the child process except
  1141. * the error passed to the callback will be an `AbortError`:
  1142. *
  1143. * ```js
  1144. * import { execFile } from 'node:child_process';
  1145. * const controller = new AbortController();
  1146. * const { signal } = controller;
  1147. * const child = execFile('node', ['--version'], { signal }, (error) => {
  1148. * console.error(error); // an AbortError
  1149. * });
  1150. * controller.abort();
  1151. * ```
  1152. * @since v0.1.91
  1153. * @param file The name or path of the executable file to run.
  1154. * @param args List of string arguments.
  1155. * @param callback Called with the output when process terminates.
  1156. */
  1157. function execFile(file: string): ChildProcess;
  1158. function execFile(
  1159. file: string,
  1160. options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null,
  1161. ): ChildProcess;
  1162. function execFile(file: string, args?: readonly string[] | null): ChildProcess;
  1163. function execFile(
  1164. file: string,
  1165. args: readonly string[] | undefined | null,
  1166. options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null,
  1167. ): ChildProcess;
  1168. // no `options` definitely means stdout/stderr are `string`.
  1169. function execFile(
  1170. file: string,
  1171. callback: (error: ExecFileException | null, stdout: string, stderr: string) => void,
  1172. ): ChildProcess;
  1173. function execFile(
  1174. file: string,
  1175. args: readonly string[] | undefined | null,
  1176. callback: (error: ExecFileException | null, stdout: string, stderr: string) => void,
  1177. ): ChildProcess;
  1178. // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`.
  1179. function execFile(
  1180. file: string,
  1181. options: ExecFileOptionsWithBufferEncoding,
  1182. callback: (error: ExecFileException | null, stdout: Buffer, stderr: Buffer) => void,
  1183. ): ChildProcess;
  1184. function execFile(
  1185. file: string,
  1186. args: readonly string[] | undefined | null,
  1187. options: ExecFileOptionsWithBufferEncoding,
  1188. callback: (error: ExecFileException | null, stdout: Buffer, stderr: Buffer) => void,
  1189. ): ChildProcess;
  1190. // `options` with well known `encoding` means stdout/stderr are definitely `string`.
  1191. function execFile(
  1192. file: string,
  1193. options: ExecFileOptionsWithStringEncoding,
  1194. callback: (error: ExecFileException | null, stdout: string, stderr: string) => void,
  1195. ): ChildProcess;
  1196. function execFile(
  1197. file: string,
  1198. args: readonly string[] | undefined | null,
  1199. options: ExecFileOptionsWithStringEncoding,
  1200. callback: (error: ExecFileException | null, stdout: string, stderr: string) => void,
  1201. ): ChildProcess;
  1202. // `options` with an `encoding` whose type is `string` means stdout/stderr could either be `Buffer` or `string`.
  1203. // There is no guarantee the `encoding` is unknown as `string` is a superset of `BufferEncoding`.
  1204. function execFile(
  1205. file: string,
  1206. options: ExecFileOptionsWithOtherEncoding,
  1207. callback: (error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void,
  1208. ): ChildProcess;
  1209. function execFile(
  1210. file: string,
  1211. args: readonly string[] | undefined | null,
  1212. options: ExecFileOptionsWithOtherEncoding,
  1213. callback: (error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void,
  1214. ): ChildProcess;
  1215. // `options` without an `encoding` means stdout/stderr are definitely `string`.
  1216. function execFile(
  1217. file: string,
  1218. options: ExecFileOptions,
  1219. callback: (error: ExecFileException | null, stdout: string, stderr: string) => void,
  1220. ): ChildProcess;
  1221. function execFile(
  1222. file: string,
  1223. args: readonly string[] | undefined | null,
  1224. options: ExecFileOptions,
  1225. callback: (error: ExecFileException | null, stdout: string, stderr: string) => void,
  1226. ): ChildProcess;
  1227. // fallback if nothing else matches. Worst case is always `string | Buffer`.
  1228. function execFile(
  1229. file: string,
  1230. options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null,
  1231. callback:
  1232. | ((error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void)
  1233. | undefined
  1234. | null,
  1235. ): ChildProcess;
  1236. function execFile(
  1237. file: string,
  1238. args: readonly string[] | undefined | null,
  1239. options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null,
  1240. callback:
  1241. | ((error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void)
  1242. | undefined
  1243. | null,
  1244. ): ChildProcess;
  1245. namespace execFile {
  1246. function __promisify__(file: string): PromiseWithChild<{
  1247. stdout: string;
  1248. stderr: string;
  1249. }>;
  1250. function __promisify__(
  1251. file: string,
  1252. args: readonly string[] | undefined | null,
  1253. ): PromiseWithChild<{
  1254. stdout: string;
  1255. stderr: string;
  1256. }>;
  1257. function __promisify__(
  1258. file: string,
  1259. options: ExecFileOptionsWithBufferEncoding,
  1260. ): PromiseWithChild<{
  1261. stdout: Buffer;
  1262. stderr: Buffer;
  1263. }>;
  1264. function __promisify__(
  1265. file: string,
  1266. args: readonly string[] | undefined | null,
  1267. options: ExecFileOptionsWithBufferEncoding,
  1268. ): PromiseWithChild<{
  1269. stdout: Buffer;
  1270. stderr: Buffer;
  1271. }>;
  1272. function __promisify__(
  1273. file: string,
  1274. options: ExecFileOptionsWithStringEncoding,
  1275. ): PromiseWithChild<{
  1276. stdout: string;
  1277. stderr: string;
  1278. }>;
  1279. function __promisify__(
  1280. file: string,
  1281. args: readonly string[] | undefined | null,
  1282. options: ExecFileOptionsWithStringEncoding,
  1283. ): PromiseWithChild<{
  1284. stdout: string;
  1285. stderr: string;
  1286. }>;
  1287. function __promisify__(
  1288. file: string,
  1289. options: ExecFileOptionsWithOtherEncoding,
  1290. ): PromiseWithChild<{
  1291. stdout: string | Buffer;
  1292. stderr: string | Buffer;
  1293. }>;
  1294. function __promisify__(
  1295. file: string,
  1296. args: readonly string[] | undefined | null,
  1297. options: ExecFileOptionsWithOtherEncoding,
  1298. ): PromiseWithChild<{
  1299. stdout: string | Buffer;
  1300. stderr: string | Buffer;
  1301. }>;
  1302. function __promisify__(
  1303. file: string,
  1304. options: ExecFileOptions,
  1305. ): PromiseWithChild<{
  1306. stdout: string;
  1307. stderr: string;
  1308. }>;
  1309. function __promisify__(
  1310. file: string,
  1311. args: readonly string[] | undefined | null,
  1312. options: ExecFileOptions,
  1313. ): PromiseWithChild<{
  1314. stdout: string;
  1315. stderr: string;
  1316. }>;
  1317. function __promisify__(
  1318. file: string,
  1319. options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null,
  1320. ): PromiseWithChild<{
  1321. stdout: string | Buffer;
  1322. stderr: string | Buffer;
  1323. }>;
  1324. function __promisify__(
  1325. file: string,
  1326. args: readonly string[] | undefined | null,
  1327. options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null,
  1328. ): PromiseWithChild<{
  1329. stdout: string | Buffer;
  1330. stderr: string | Buffer;
  1331. }>;
  1332. }
  1333. interface ForkOptions extends ProcessEnvOptions, MessagingOptions, Abortable {
  1334. execPath?: string | undefined;
  1335. execArgv?: string[] | undefined;
  1336. silent?: boolean | undefined;
  1337. /**
  1338. * Can be set to 'pipe', 'inherit', 'overlapped', or 'ignore', or an array of these strings.
  1339. * If passed as an array, the first element is used for `stdin`, the second for
  1340. * `stdout`, and the third for `stderr`. A fourth element can be used to
  1341. * specify the `stdio` behavior beyond the standard streams. See
  1342. * {@link ChildProcess.stdio} for more information.
  1343. *
  1344. * @default 'pipe'
  1345. */
  1346. stdio?: StdioOptions | undefined;
  1347. detached?: boolean | undefined;
  1348. windowsVerbatimArguments?: boolean | undefined;
  1349. }
  1350. /**
  1351. * The `child_process.fork()` method is a special case of {@link spawn} used specifically to spawn new Node.js processes.
  1352. * Like {@link spawn}, a `ChildProcess` object is returned. The
  1353. * returned `ChildProcess` will have an additional communication channel
  1354. * built-in that allows messages to be passed back and forth between the parent and
  1355. * child. See `subprocess.send()` for details.
  1356. *
  1357. * Keep in mind that spawned Node.js child processes are
  1358. * independent of the parent with exception of the IPC communication channel
  1359. * that is established between the two. Each process has its own memory, with
  1360. * their own V8 instances. Because of the additional resource allocations
  1361. * required, spawning a large number of child Node.js processes is not
  1362. * recommended.
  1363. *
  1364. * By default, `child_process.fork()` will spawn new Node.js instances using the `process.execPath` of the parent process. The `execPath` property in the `options` object allows for an alternative
  1365. * execution path to be used.
  1366. *
  1367. * Node.js processes launched with a custom `execPath` will communicate with the
  1368. * parent process using the file descriptor (fd) identified using the
  1369. * environment variable `NODE_CHANNEL_FD` on the child process.
  1370. *
  1371. * Unlike the [`fork(2)`](http://man7.org/linux/man-pages/man2/fork.2.html) POSIX system call, `child_process.fork()` does not clone the
  1372. * current process.
  1373. *
  1374. * The `shell` option available in {@link spawn} is not supported by `child_process.fork()` and will be ignored if set.
  1375. *
  1376. * If the `signal` option is enabled, calling `.abort()` on the corresponding `AbortController` is similar to calling `.kill()` on the child process except
  1377. * the error passed to the callback will be an `AbortError`:
  1378. *
  1379. * ```js
  1380. * if (process.argv[2] === 'child') {
  1381. * setTimeout(() => {
  1382. * console.log(`Hello from ${process.argv[2]}!`);
  1383. * }, 1_000);
  1384. * } else {
  1385. * import { fork } from 'node:child_process';
  1386. * const controller = new AbortController();
  1387. * const { signal } = controller;
  1388. * const child = fork(__filename, ['child'], { signal });
  1389. * child.on('error', (err) => {
  1390. * // This will be called with err being an AbortError if the controller aborts
  1391. * });
  1392. * controller.abort(); // Stops the child process
  1393. * }
  1394. * ```
  1395. * @since v0.5.0
  1396. * @param modulePath The module to run in the child.
  1397. * @param args List of string arguments.
  1398. */
  1399. function fork(modulePath: string | URL, options?: ForkOptions): ChildProcess;
  1400. function fork(modulePath: string | URL, args?: readonly string[], options?: ForkOptions): ChildProcess;
  1401. interface SpawnSyncOptions extends CommonSpawnOptions {
  1402. input?: string | NodeJS.ArrayBufferView | undefined;
  1403. maxBuffer?: number | undefined;
  1404. encoding?: BufferEncoding | "buffer" | null | undefined;
  1405. }
  1406. interface SpawnSyncOptionsWithStringEncoding extends SpawnSyncOptions {
  1407. encoding: BufferEncoding;
  1408. }
  1409. interface SpawnSyncOptionsWithBufferEncoding extends SpawnSyncOptions {
  1410. encoding?: "buffer" | null | undefined;
  1411. }
  1412. interface SpawnSyncReturns<T> {
  1413. pid: number;
  1414. output: Array<T | null>;
  1415. stdout: T;
  1416. stderr: T;
  1417. status: number | null;
  1418. signal: NodeJS.Signals | null;
  1419. error?: Error | undefined;
  1420. }
  1421. /**
  1422. * The `child_process.spawnSync()` method is generally identical to {@link spawn} with the exception that the function will not return
  1423. * until the child process has fully closed. When a timeout has been encountered
  1424. * and `killSignal` is sent, the method won't return until the process has
  1425. * completely exited. If the process intercepts and handles the `SIGTERM` signal
  1426. * and doesn't exit, the parent process will wait until the child process has
  1427. * exited.
  1428. *
  1429. * **If the `shell` option is enabled, do not pass unsanitized user input to this**
  1430. * **function. Any input containing shell metacharacters may be used to trigger**
  1431. * **arbitrary command execution.**
  1432. * @since v0.11.12
  1433. * @param command The command to run.
  1434. * @param args List of string arguments.
  1435. */
  1436. function spawnSync(command: string): SpawnSyncReturns<Buffer>;
  1437. function spawnSync(command: string, options: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns<string>;
  1438. function spawnSync(command: string, options: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns<Buffer>;
  1439. function spawnSync(command: string, options?: SpawnSyncOptions): SpawnSyncReturns<string | Buffer>;
  1440. function spawnSync(command: string, args: readonly string[]): SpawnSyncReturns<Buffer>;
  1441. function spawnSync(
  1442. command: string,
  1443. args: readonly string[],
  1444. options: SpawnSyncOptionsWithStringEncoding,
  1445. ): SpawnSyncReturns<string>;
  1446. function spawnSync(
  1447. command: string,
  1448. args: readonly string[],
  1449. options: SpawnSyncOptionsWithBufferEncoding,
  1450. ): SpawnSyncReturns<Buffer>;
  1451. function spawnSync(
  1452. command: string,
  1453. args?: readonly string[],
  1454. options?: SpawnSyncOptions,
  1455. ): SpawnSyncReturns<string | Buffer>;
  1456. interface CommonExecOptions extends CommonOptions {
  1457. input?: string | NodeJS.ArrayBufferView | undefined;
  1458. /**
  1459. * Can be set to 'pipe', 'inherit, or 'ignore', or an array of these strings.
  1460. * If passed as an array, the first element is used for `stdin`, the second for
  1461. * `stdout`, and the third for `stderr`. A fourth element can be used to
  1462. * specify the `stdio` behavior beyond the standard streams. See
  1463. * {@link ChildProcess.stdio} for more information.
  1464. *
  1465. * @default 'pipe'
  1466. */
  1467. stdio?: StdioOptions | undefined;
  1468. killSignal?: NodeJS.Signals | number | undefined;
  1469. maxBuffer?: number | undefined;
  1470. encoding?: BufferEncoding | "buffer" | null | undefined;
  1471. }
  1472. interface ExecSyncOptions extends CommonExecOptions {
  1473. shell?: string | undefined;
  1474. }
  1475. interface ExecSyncOptionsWithStringEncoding extends ExecSyncOptions {
  1476. encoding: BufferEncoding;
  1477. }
  1478. interface ExecSyncOptionsWithBufferEncoding extends ExecSyncOptions {
  1479. encoding?: "buffer" | null | undefined;
  1480. }
  1481. /**
  1482. * The `child_process.execSync()` method is generally identical to {@link exec} with the exception that the method will not return
  1483. * until the child process has fully closed. When a timeout has been encountered
  1484. * and `killSignal` is sent, the method won't return until the process has
  1485. * completely exited. If the child process intercepts and handles the `SIGTERM` signal and doesn't exit, the parent process will wait until the child process
  1486. * has exited.
  1487. *
  1488. * If the process times out or has a non-zero exit code, this method will throw.
  1489. * The `Error` object will contain the entire result from {@link spawnSync}.
  1490. *
  1491. * **Never pass unsanitized user input to this function. Any input containing shell**
  1492. * **metacharacters may be used to trigger arbitrary command execution.**
  1493. * @since v0.11.12
  1494. * @param command The command to run.
  1495. * @return The stdout from the command.
  1496. */
  1497. function execSync(command: string): Buffer;
  1498. function execSync(command: string, options: ExecSyncOptionsWithStringEncoding): string;
  1499. function execSync(command: string, options: ExecSyncOptionsWithBufferEncoding): Buffer;
  1500. function execSync(command: string, options?: ExecSyncOptions): string | Buffer;
  1501. interface ExecFileSyncOptions extends CommonExecOptions {
  1502. shell?: boolean | string | undefined;
  1503. }
  1504. interface ExecFileSyncOptionsWithStringEncoding extends ExecFileSyncOptions {
  1505. encoding: BufferEncoding;
  1506. }
  1507. interface ExecFileSyncOptionsWithBufferEncoding extends ExecFileSyncOptions {
  1508. encoding?: "buffer" | null; // specify `null`.
  1509. }
  1510. /**
  1511. * The `child_process.execFileSync()` method is generally identical to {@link execFile} with the exception that the method will not
  1512. * return until the child process has fully closed. When a timeout has been
  1513. * encountered and `killSignal` is sent, the method won't return until the process
  1514. * has completely exited.
  1515. *
  1516. * If the child process intercepts and handles the `SIGTERM` signal and
  1517. * does not exit, the parent process will still wait until the child process has
  1518. * exited.
  1519. *
  1520. * If the process times out or has a non-zero exit code, this method will throw an `Error` that will include the full result of the underlying {@link spawnSync}.
  1521. *
  1522. * **If the `shell` option is enabled, do not pass unsanitized user input to this**
  1523. * **function. Any input containing shell metacharacters may be used to trigger**
  1524. * **arbitrary command execution.**
  1525. * @since v0.11.12
  1526. * @param file The name or path of the executable file to run.
  1527. * @param args List of string arguments.
  1528. * @return The stdout from the command.
  1529. */
  1530. function execFileSync(file: string): Buffer;
  1531. function execFileSync(file: string, options: ExecFileSyncOptionsWithStringEncoding): string;
  1532. function execFileSync(file: string, options: ExecFileSyncOptionsWithBufferEncoding): Buffer;
  1533. function execFileSync(file: string, options?: ExecFileSyncOptions): string | Buffer;
  1534. function execFileSync(file: string, args: readonly string[]): Buffer;
  1535. function execFileSync(
  1536. file: string,
  1537. args: readonly string[],
  1538. options: ExecFileSyncOptionsWithStringEncoding,
  1539. ): string;
  1540. function execFileSync(
  1541. file: string,
  1542. args: readonly string[],
  1543. options: ExecFileSyncOptionsWithBufferEncoding,
  1544. ): Buffer;
  1545. function execFileSync(file: string, args?: readonly string[], options?: ExecFileSyncOptions): string | Buffer;
  1546. }
  1547. declare module "node:child_process" {
  1548. export * from "child_process";
  1549. }