af6555d004250b063b3103a82ad6f9eddf49f283d7e5793ec45841425952a4a749fb661e31000e655b8cf7cb3e9530e9ee85df108f3805418ff279085fd145 64 KB

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