1 | /**
|
2 | * The `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 | * const { spawn } = require('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 it is in the `options` object. Otherwise, `process.env.PATH` is
|
32 | * used.
|
33 | *
|
34 | * On Windows, environment variables are case-insensitive. Node.js
|
35 | * lexicographically sorts the `env` keys and uses the first one that
|
36 | * case-insensitively matches. Only first (in lexicographic order) entry will be
|
37 | * passed to the subprocess. This might lead to issues on Windows when passing
|
38 | * objects to the `env` option that have multiple variants of the same key, such as`PATH` and `Path`.
|
39 | *
|
40 | * The {@link spawn} method spawns the child process asynchronously,
|
41 | * without blocking the Node.js event loop. The {@link spawnSync} function provides equivalent functionality in a synchronous manner that blocks
|
42 | * the event loop until the spawned process either exits or is terminated.
|
43 | *
|
44 | * For convenience, the `child_process` module provides a handful of synchronous
|
45 | * and asynchronous alternatives to {@link spawn} and {@link spawnSync}. Each of these alternatives are implemented on
|
46 | * top of {@link spawn} or {@link spawnSync}.
|
47 | *
|
48 | * * {@link exec}: spawns a shell and runs a command within that
|
49 | * shell, passing the `stdout` and `stderr` to a callback function when
|
50 | * complete.
|
51 | * * {@link execFile}: similar to {@link exec} except
|
52 | * that it spawns the command directly without first spawning a shell by
|
53 | * default.
|
54 | * * {@link fork}: spawns a new Node.js process and invokes a
|
55 | * specified module with an IPC communication channel established that allows
|
56 | * sending messages between parent and child.
|
57 | * * {@link execSync}: a synchronous version of {@link exec} that will block the Node.js event loop.
|
58 | * * {@link execFileSync}: a synchronous version of {@link execFile} that will block the Node.js event loop.
|
59 | *
|
60 | * For certain use cases, such as automating shell scripts, the `synchronous counterparts` may be more convenient. In many cases, however,
|
61 | * the synchronous methods can have significant impact on performance due to
|
62 | * stalling the event loop while spawned processes complete.
|
63 | * @see [source](https://github.com/nodejs/node/blob/v17.0.0/lib/child_process.js)
|
64 | */
|
65 | declare module 'child_process' {
|
66 | import { ObjectEncodingOptions } from 'node:fs';
|
67 | import { EventEmitter, Abortable } from 'node:events';
|
68 | import * as net from 'node:net';
|
69 | import { Writable, Readable, Stream, Pipe } from 'node:stream';
|
70 | import { URL } from 'node:url';
|
71 | type Serializable = string | object | number | boolean | bigint;
|
72 | type SendHandle = net.Socket | net.Server;
|
73 | /**
|
74 | * Instances of the `ChildProcess` represent spawned child processes.
|
75 | *
|
76 | * Instances of `ChildProcess` are not intended to be created directly. Rather,
|
77 | * use the {@link spawn}, {@link exec},{@link execFile}, or {@link fork} methods to create
|
78 | * instances of `ChildProcess`.
|
79 | * @since v2.2.0
|
80 | */
|
81 | class ChildProcess extends EventEmitter {
|
82 | /**
|
83 | * A `Writable Stream` that represents the child process's `stdin`.
|
84 | *
|
85 | * If a child process waits to read all of its input, the child will not continue
|
86 | * until this stream has been closed via `end()`.
|
87 | *
|
88 | * If the child was spawned with `stdio[0]` set to anything other than `'pipe'`,
|
89 | * then this will be `null`.
|
90 | *
|
91 | * `subprocess.stdin` is an alias for `subprocess.stdio[0]`. Both properties will
|
92 | * refer to the same value.
|
93 | *
|
94 | * The `subprocess.stdin` property can be `undefined` if the child process could
|
95 | * not be successfully spawned.
|
96 | * @since v0.1.90
|
97 | */
|
98 | stdin: Writable | null;
|
99 | /**
|
100 | * A `Readable Stream` that represents the child process's `stdout`.
|
101 | *
|
102 | * If the child was spawned with `stdio[1]` set to anything other than `'pipe'`,
|
103 | * then this will be `null`.
|
104 | *
|
105 | * `subprocess.stdout` is an alias for `subprocess.stdio[1]`. Both properties will
|
106 | * refer to the same value.
|
107 | *
|
108 | * ```js
|
109 | * const { spawn } = require('child_process');
|
110 | *
|
111 | * const subprocess = spawn('ls');
|
112 | *
|
113 | * subprocess.stdout.on('data', (data) => {
|
114 | * console.log(`Received chunk ${data}`);
|
115 | * });
|
116 | * ```
|
117 | *
|
118 | * The `subprocess.stdout` property can be `null` if the child process could
|
119 | * not be successfully spawned.
|
120 | * @since v0.1.90
|
121 | */
|
122 | stdout: Readable | null;
|
123 | /**
|
124 | * A `Readable Stream` that represents the child process's `stderr`.
|
125 | *
|
126 | * If the child was spawned with `stdio[2]` set to anything other than `'pipe'`,
|
127 | * then this will be `null`.
|
128 | *
|
129 | * `subprocess.stderr` is an alias for `subprocess.stdio[2]`. Both properties will
|
130 | * refer to the same value.
|
131 | *
|
132 | * The `subprocess.stderr` property can be `null` if the child process could
|
133 | * 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 currently 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 | * const assert = require('assert');
|
155 | * const fs = require('fs');
|
156 | * const child_process = require('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 | * const { spawn } = require('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 | * const { spawn } = require('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 | * const { spawn } = require('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 | * When an IPC channel has been established between the parent and child (
|
307 | * i.e. when using {@link fork}), the `subprocess.send()` method can
|
308 | * be used to send messages to the child process. When the child process is a
|
309 | * Node.js instance, these messages can be received via the `'message'` event.
|
310 | *
|
311 | * The message goes through serialization and parsing. The resulting
|
312 | * message might not be the same as what is originally sent.
|
313 | *
|
314 | * For example, in the parent script:
|
315 | *
|
316 | * ```js
|
317 | * const cp = require('child_process');
|
318 | * const n = cp.fork(`${__dirname}/sub.js`);
|
319 | *
|
320 | * n.on('message', (m) => {
|
321 | * console.log('PARENT got message:', m);
|
322 | * });
|
323 | *
|
324 | * // Causes the child to print: CHILD got message: { hello: 'world' }
|
325 | * n.send({ hello: 'world' });
|
326 | * ```
|
327 | *
|
328 | * And then the child script, `'sub.js'` might look like this:
|
329 | *
|
330 | * ```js
|
331 | * process.on('message', (m) => {
|
332 | * console.log('CHILD got message:', m);
|
333 | * });
|
334 | *
|
335 | * // Causes the parent to print: PARENT got message: { foo: 'bar', baz: null }
|
336 | * process.send({ foo: 'bar', baz: NaN });
|
337 | * ```
|
338 | *
|
339 | * Child Node.js processes will have a `process.send()` method of their own
|
340 | * that allows the child to send messages back to the parent.
|
341 | *
|
342 | * There is a special case when sending a `{cmd: 'NODE_foo'}` message. Messages
|
343 | * containing a `NODE_` prefix in the `cmd` property are reserved for use within
|
344 | * 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.
|
345 | * Applications should avoid using such messages or listening for`'internalMessage'` events as it is subject to change without notice.
|
346 | *
|
347 | * The optional `sendHandle` argument that may be passed to `subprocess.send()` is
|
348 | * for passing a TCP server or socket object to the child process. The child will
|
349 | * receive the object as the second argument passed to the callback function
|
350 | * registered on the `'message'` event. Any data that is received
|
351 | * and buffered in the socket will not be sent to the child.
|
352 | *
|
353 | * The optional `callback` is a function that is invoked after the message is
|
354 | * sent but before the child may have received it. The function is called with a
|
355 | * single argument: `null` on success, or an `Error` object on failure.
|
356 | *
|
357 | * If no `callback` function is provided and the message cannot be sent, an`'error'` event will be emitted by the `ChildProcess` object. This can
|
358 | * happen, for instance, when the child process has already exited.
|
359 | *
|
360 | * `subprocess.send()` will return `false` if the channel has closed or when the
|
361 | * backlog of unsent messages exceeds a threshold that makes it unwise to send
|
362 | * more. Otherwise, the method returns `true`. The `callback` function can be
|
363 | * used to implement flow control.
|
364 | *
|
365 | * #### Example: sending a server object
|
366 | *
|
367 | * The `sendHandle` argument can be used, for instance, to pass the handle of
|
368 | * a TCP server object to the child process as illustrated in the example below:
|
369 | *
|
370 | * ```js
|
371 | * const subprocess = require('child_process').fork('subprocess.js');
|
372 | *
|
373 | * // Open up the server object and send the handle.
|
374 | * const server = require('net').createServer();
|
375 | * server.on('connection', (socket) => {
|
376 | * socket.end('handled by parent');
|
377 | * });
|
378 | * server.listen(1337, () => {
|
379 | * subprocess.send('server', server);
|
380 | * });
|
381 | * ```
|
382 | *
|
383 | * The child would then receive the server object as:
|
384 | *
|
385 | * ```js
|
386 | * process.on('message', (m, server) => {
|
387 | * if (m === 'server') {
|
388 | * server.on('connection', (socket) => {
|
389 | * socket.end('handled by child');
|
390 | * });
|
391 | * }
|
392 | * });
|
393 | * ```
|
394 | *
|
395 | * Once the server is now shared between the parent and child, some connections
|
396 | * can be handled by the parent and some by the child.
|
397 | *
|
398 | * While the example above uses a server created using the `net` module, `dgram`module servers use exactly the same workflow with the exceptions of listening on
|
399 | * a `'message'` event instead of `'connection'` and using `server.bind()` instead
|
400 | * of `server.listen()`. This is, however, currently only supported on Unix
|
401 | * platforms.
|
402 | *
|
403 | * #### Example: sending a socket object
|
404 | *
|
405 | * Similarly, the `sendHandler` argument can be used to pass the handle of a
|
406 | * socket to the child process. The example below spawns two children that each
|
407 | * handle connections with "normal" or "special" priority:
|
408 | *
|
409 | * ```js
|
410 | * const { fork } = require('child_process');
|
411 | * const normal = fork('subprocess.js', ['normal']);
|
412 | * const special = fork('subprocess.js', ['special']);
|
413 | *
|
414 | * // Open up the server and send sockets to child. Use pauseOnConnect to prevent
|
415 | * // the sockets from being read before they are sent to the child process.
|
416 | * const server = require('net').createServer({ pauseOnConnect: true });
|
417 | * server.on('connection', (socket) => {
|
418 | *
|
419 | * // If this is special priority...
|
420 | * if (socket.remoteAddress === '74.125.127.100') {
|
421 | * special.send('socket', socket);
|
422 | * return;
|
423 | * }
|
424 | * // This is normal priority.
|
425 | * normal.send('socket', socket);
|
426 | * });
|
427 | * server.listen(1337);
|
428 | * ```
|
429 | *
|
430 | * The `subprocess.js` would receive the socket handle as the second argument
|
431 | * passed to the event callback function:
|
432 | *
|
433 | * ```js
|
434 | * process.on('message', (m, socket) => {
|
435 | * if (m === 'socket') {
|
436 | * if (socket) {
|
437 | * // Check that the client socket exists.
|
438 | * // It is possible for the socket to be closed between the time it is
|
439 | * // sent and the time it is received in the child process.
|
440 | * socket.end(`Request handled with ${process.argv[2]} priority`);
|
441 | * }
|
442 | * }
|
443 | * });
|
444 | * ```
|
445 | *
|
446 | * Do not use `.maxConnections` on a socket that has been passed to a subprocess.
|
447 | * The parent cannot track when the socket is destroyed.
|
448 | *
|
449 | * Any `'message'` handlers in the subprocess should verify that `socket` exists,
|
450 | * as the connection may have been closed during the time it takes to send the
|
451 | * connection to the child.
|
452 | * @since v0.5.9
|
453 | * @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:
|
454 | */
|
455 | send(message: Serializable, callback?: (error: Error | null) => void): boolean;
|
456 | send(message: Serializable, sendHandle?: SendHandle, callback?: (error: Error | null) => void): boolean;
|
457 | send(message: Serializable, sendHandle?: SendHandle, options?: MessageOptions, callback?: (error: Error | null) => void): boolean;
|
458 | /**
|
459 | * Closes the IPC channel between parent and child, allowing the child to exit
|
460 | * gracefully once there are no other connections keeping it alive. After calling
|
461 | * this method the `subprocess.connected` and `process.connected` properties in
|
462 | * both the parent and child (respectively) will be set to `false`, and it will be
|
463 | * no longer possible to pass messages between the processes.
|
464 | *
|
465 | * The `'disconnect'` event will be emitted when there are no messages in the
|
466 | * process of being received. This will most often be triggered immediately after
|
467 | * calling `subprocess.disconnect()`.
|
468 | *
|
469 | * When the child process is a Node.js instance (e.g. spawned using {@link fork}), the `process.disconnect()` method can be invoked
|
470 | * within the child process to close the IPC channel as well.
|
471 | * @since v0.7.2
|
472 | */
|
473 | disconnect(): void;
|
474 | /**
|
475 | * By default, the parent will wait for the detached child to exit. To prevent the
|
476 | * 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
|
477 | * include the child in its reference count, allowing the parent to exit
|
478 | * independently of the child, unless there is an established IPC channel between
|
479 | * the child and the parent.
|
480 | *
|
481 | * ```js
|
482 | * const { spawn } = require('child_process');
|
483 | *
|
484 | * const subprocess = spawn(process.argv[0], ['child_program.js'], {
|
485 | * detached: true,
|
486 | * stdio: 'ignore'
|
487 | * });
|
488 | *
|
489 | * subprocess.unref();
|
490 | * ```
|
491 | * @since v0.7.10
|
492 | */
|
493 | unref(): void;
|
494 | /**
|
495 | * Calling `subprocess.ref()` after making a call to `subprocess.unref()` will
|
496 | * restore the removed reference count for the child process, forcing the parent
|
497 | * to wait for the child to exit before exiting itself.
|
498 | *
|
499 | * ```js
|
500 | * const { spawn } = require('child_process');
|
501 | *
|
502 | * const subprocess = spawn(process.argv[0], ['child_program.js'], {
|
503 | * detached: true,
|
504 | * stdio: 'ignore'
|
505 | * });
|
506 | *
|
507 | * subprocess.unref();
|
508 | * subprocess.ref();
|
509 | * ```
|
510 | * @since v0.7.10
|
511 | */
|
512 | ref(): void;
|
513 | /**
|
514 | * events.EventEmitter
|
515 | * 1. close
|
516 | * 2. disconnect
|
517 | * 3. error
|
518 | * 4. exit
|
519 | * 5. message
|
520 | * 6. spawn
|
521 | */
|
522 | addListener(event: string, listener: (...args: any[]) => void): this;
|
523 | addListener(event: 'close', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this;
|
524 | addListener(event: 'disconnect', listener: () => void): this;
|
525 | addListener(event: 'error', listener: (err: Error) => void): this;
|
526 | addListener(event: 'exit', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this;
|
527 | addListener(event: 'message', listener: (message: Serializable, sendHandle: SendHandle) => void): this;
|
528 | addListener(event: 'spawn', listener: () => void): this;
|
529 | emit(event: string | symbol, ...args: any[]): boolean;
|
530 | emit(event: 'close', code: number | null, signal: NodeJS.Signals | null): boolean;
|
531 | emit(event: 'disconnect'): boolean;
|
532 | emit(event: 'error', err: Error): boolean;
|
533 | emit(event: 'exit', code: number | null, signal: NodeJS.Signals | null): boolean;
|
534 | emit(event: 'message', message: Serializable, sendHandle: SendHandle): boolean;
|
535 | emit(event: 'spawn', listener: () => void): boolean;
|
536 | on(event: string, listener: (...args: any[]) => void): this;
|
537 | on(event: 'close', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this;
|
538 | on(event: 'disconnect', listener: () => void): this;
|
539 | on(event: 'error', listener: (err: Error) => void): this;
|
540 | on(event: 'exit', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this;
|
541 | on(event: 'message', listener: (message: Serializable, sendHandle: SendHandle) => void): this;
|
542 | on(event: 'spawn', listener: () => void): this;
|
543 | once(event: string, listener: (...args: any[]) => void): this;
|
544 | once(event: 'close', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this;
|
545 | once(event: 'disconnect', listener: () => void): this;
|
546 | once(event: 'error', listener: (err: Error) => void): this;
|
547 | once(event: 'exit', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this;
|
548 | once(event: 'message', listener: (message: Serializable, sendHandle: SendHandle) => void): this;
|
549 | once(event: 'spawn', listener: () => void): this;
|
550 | prependListener(event: string, listener: (...args: any[]) => void): this;
|
551 | prependListener(event: 'close', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this;
|
552 | prependListener(event: 'disconnect', listener: () => void): this;
|
553 | prependListener(event: 'error', listener: (err: Error) => void): this;
|
554 | prependListener(event: 'exit', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this;
|
555 | prependListener(event: 'message', listener: (message: Serializable, sendHandle: SendHandle) => void): this;
|
556 | prependListener(event: 'spawn', listener: () => void): this;
|
557 | prependOnceListener(event: string, listener: (...args: any[]) => void): this;
|
558 | prependOnceListener(event: 'close', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this;
|
559 | prependOnceListener(event: 'disconnect', listener: () => void): this;
|
560 | prependOnceListener(event: 'error', listener: (err: Error) => void): this;
|
561 | prependOnceListener(event: 'exit', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this;
|
562 | prependOnceListener(event: 'message', listener: (message: Serializable, sendHandle: SendHandle) => void): this;
|
563 | prependOnceListener(event: 'spawn', listener: () => void): this;
|
564 | }
|
565 | // return this object when stdio option is undefined or not specified
|
566 | interface ChildProcessWithoutNullStreams extends ChildProcess {
|
567 | stdin: Writable;
|
568 | stdout: Readable;
|
569 | stderr: Readable;
|
570 | readonly stdio: [
|
571 | Writable,
|
572 | Readable,
|
573 | Readable,
|
574 | // stderr
|
575 | Readable | Writable | null | undefined,
|
576 | // extra, no modification
|
577 | Readable | Writable | null | undefined // extra, no modification
|
578 | ];
|
579 | }
|
580 | // return this object when stdio option is a tuple of 3
|
581 | interface ChildProcessByStdio<I extends null | Writable, O extends null | Readable, E extends null | Readable> extends ChildProcess {
|
582 | stdin: I;
|
583 | stdout: O;
|
584 | stderr: E;
|
585 | readonly stdio: [
|
586 | I,
|
587 | O,
|
588 | E,
|
589 | Readable | Writable | null | undefined,
|
590 | // extra, no modification
|
591 | Readable | Writable | null | undefined // extra, no modification
|
592 | ];
|
593 | }
|
594 | interface MessageOptions {
|
595 | keepOpen?: boolean | undefined;
|
596 | }
|
597 | type IOType = 'overlapped' | 'pipe' | 'ignore' | 'inherit';
|
598 | type StdioOptions = IOType | Array<IOType | 'ipc' | Stream | number | null | undefined>;
|
599 | type SerializationType = 'json' | 'advanced';
|
600 | interface MessagingOptions extends Abortable {
|
601 | /**
|
602 | * Specify the kind of serialization used for sending messages between processes.
|
603 | * @default 'json'
|
604 | */
|
605 | serialization?: SerializationType | undefined;
|
606 | /**
|
607 | * The signal value to be used when the spawned process will be killed by the abort signal.
|
608 | * @default 'SIGTERM'
|
609 | */
|
610 | killSignal?: NodeJS.Signals | number | undefined;
|
611 | /**
|
612 | * In milliseconds the maximum amount of time the process is allowed to run.
|
613 | */
|
614 | timeout?: number | undefined;
|
615 | }
|
616 | interface ProcessEnvOptions {
|
617 | uid?: number | undefined;
|
618 | gid?: number | undefined;
|
619 | cwd?: string | URL | undefined;
|
620 | env?: NodeJS.ProcessEnv | undefined;
|
621 | }
|
622 | interface CommonOptions extends ProcessEnvOptions {
|
623 | /**
|
624 | * @default true
|
625 | */
|
626 | windowsHide?: boolean | undefined;
|
627 | /**
|
628 | * @default 0
|
629 | */
|
630 | timeout?: number | undefined;
|
631 | }
|
632 | interface CommonSpawnOptions extends CommonOptions, MessagingOptions, Abortable {
|
633 | argv0?: string | undefined;
|
634 | stdio?: StdioOptions | undefined;
|
635 | shell?: boolean | string | undefined;
|
636 | windowsVerbatimArguments?: boolean | undefined;
|
637 | }
|
638 | interface SpawnOptions extends CommonSpawnOptions {
|
639 | detached?: boolean | undefined;
|
640 | }
|
641 | interface SpawnOptionsWithoutStdio extends SpawnOptions {
|
642 | stdio?: StdioPipeNamed | StdioPipe[] | undefined;
|
643 | }
|
644 | type StdioNull = 'inherit' | 'ignore' | Stream;
|
645 | type StdioPipeNamed = 'pipe' | 'overlapped';
|
646 | type StdioPipe = undefined | null | StdioPipeNamed;
|
647 | interface SpawnOptionsWithStdioTuple<Stdin extends StdioNull | StdioPipe, Stdout extends StdioNull | StdioPipe, Stderr extends StdioNull | StdioPipe> extends SpawnOptions {
|
648 | stdio: [Stdin, Stdout, Stderr];
|
649 | }
|
650 | /**
|
651 | * The `child_process.spawn()` method spawns a new process using the given`command`, with command-line arguments in `args`. If omitted, `args` defaults
|
652 | * to an empty array.
|
653 | *
|
654 | * **If the `shell` option is enabled, do not pass unsanitized user input to this**
|
655 | * **function. Any input containing shell metacharacters may be used to trigger**
|
656 | * **arbitrary command execution.**
|
657 | *
|
658 | * A third argument may be used to specify additional options, with these defaults:
|
659 | *
|
660 | * ```js
|
661 | * const defaults = {
|
662 | * cwd: undefined,
|
663 | * env: process.env
|
664 | * };
|
665 | * ```
|
666 | *
|
667 | * Use `cwd` to specify the working directory from which the process is spawned.
|
668 | * If not given, the default is to inherit the current working directory. If given,
|
669 | * but the path does not exist, the child process emits an `ENOENT` error
|
670 | * and exits immediately. `ENOENT` is also emitted when the command
|
671 | * does not exist.
|
672 | *
|
673 | * Use `env` to specify environment variables that will be visible to the new
|
674 | * process, the default is `process.env`.
|
675 | *
|
676 | * `undefined` values in `env` will be ignored.
|
677 | *
|
678 | * Example of running `ls -lh /usr`, capturing `stdout`, `stderr`, and the
|
679 | * exit code:
|
680 | *
|
681 | * ```js
|
682 | * const { spawn } = require('child_process');
|
683 | * const ls = spawn('ls', ['-lh', '/usr']);
|
684 | *
|
685 | * ls.stdout.on('data', (data) => {
|
686 | * console.log(`stdout: ${data}`);
|
687 | * });
|
688 | *
|
689 | * ls.stderr.on('data', (data) => {
|
690 | * console.error(`stderr: ${data}`);
|
691 | * });
|
692 | *
|
693 | * ls.on('close', (code) => {
|
694 | * console.log(`child process exited with code ${code}`);
|
695 | * });
|
696 | * ```
|
697 | *
|
698 | * Example: A very elaborate way to run `ps ax | grep ssh`
|
699 | *
|
700 | * ```js
|
701 | * const { spawn } = require('child_process');
|
702 | * const ps = spawn('ps', ['ax']);
|
703 | * const grep = spawn('grep', ['ssh']);
|
704 | *
|
705 | * ps.stdout.on('data', (data) => {
|
706 | * grep.stdin.write(data);
|
707 | * });
|
708 | *
|
709 | * ps.stderr.on('data', (data) => {
|
710 | * console.error(`ps stderr: ${data}`);
|
711 | * });
|
712 | *
|
713 | * ps.on('close', (code) => {
|
714 | * if (code !== 0) {
|
715 | * console.log(`ps process exited with code ${code}`);
|
716 | * }
|
717 | * grep.stdin.end();
|
718 | * });
|
719 | *
|
720 | * grep.stdout.on('data', (data) => {
|
721 | * console.log(data.toString());
|
722 | * });
|
723 | *
|
724 | * grep.stderr.on('data', (data) => {
|
725 | * console.error(`grep stderr: ${data}`);
|
726 | * });
|
727 | *
|
728 | * grep.on('close', (code) => {
|
729 | * if (code !== 0) {
|
730 | * console.log(`grep process exited with code ${code}`);
|
731 | * }
|
732 | * });
|
733 | * ```
|
734 | *
|
735 | * Example of checking for failed `spawn`:
|
736 | *
|
737 | * ```js
|
738 | * const { spawn } = require('child_process');
|
739 | * const subprocess = spawn('bad_command');
|
740 | *
|
741 | * subprocess.on('error', (err) => {
|
742 | * console.error('Failed to start subprocess.');
|
743 | * });
|
744 | * ```
|
745 | *
|
746 | * Certain platforms (macOS, Linux) will use the value of `argv[0]` for the process
|
747 | * title while others (Windows, SunOS) will use `command`.
|
748 | *
|
749 | * Node.js currently 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,
|
750 | * retrieve it with the`process.argv0` property instead.
|
751 | *
|
752 | * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.kill()` on the child process except
|
753 | * the error passed to the callback will be an `AbortError`:
|
754 | *
|
755 | * ```js
|
756 | * const { spawn } = require('child_process');
|
757 | * const controller = new AbortController();
|
758 | * const { signal } = controller;
|
759 | * const grep = spawn('grep', ['ssh'], { signal });
|
760 | * grep.on('error', (err) => {
|
761 | * // This will be called with err being an AbortError if the controller aborts
|
762 | * });
|
763 | * controller.abort(); // Stops the child process
|
764 | * ```
|
765 | * @since v0.1.90
|
766 | * @param command The command to run.
|
767 | * @param args List of string arguments.
|
768 | */
|
769 | function spawn(command: string, options?: SpawnOptionsWithoutStdio): ChildProcessWithoutNullStreams;
|
770 | function spawn(command: string, options: SpawnOptionsWithStdioTuple<StdioPipe, StdioPipe, StdioPipe>): ChildProcessByStdio<Writable, Readable, Readable>;
|
771 | function spawn(command: string, options: SpawnOptionsWithStdioTuple<StdioPipe, StdioPipe, StdioNull>): ChildProcessByStdio<Writable, Readable, null>;
|
772 | function spawn(command: string, options: SpawnOptionsWithStdioTuple<StdioPipe, StdioNull, StdioPipe>): ChildProcessByStdio<Writable, null, Readable>;
|
773 | function spawn(command: string, options: SpawnOptionsWithStdioTuple<StdioNull, StdioPipe, StdioPipe>): ChildProcessByStdio<null, Readable, Readable>;
|
774 | function spawn(command: string, options: SpawnOptionsWithStdioTuple<StdioPipe, StdioNull, StdioNull>): ChildProcessByStdio<Writable, null, null>;
|
775 | function spawn(command: string, options: SpawnOptionsWithStdioTuple<StdioNull, StdioPipe, StdioNull>): ChildProcessByStdio<null, Readable, null>;
|
776 | function spawn(command: string, options: SpawnOptionsWithStdioTuple<StdioNull, StdioNull, StdioPipe>): ChildProcessByStdio<null, null, Readable>;
|
777 | function spawn(command: string, options: SpawnOptionsWithStdioTuple<StdioNull, StdioNull, StdioNull>): ChildProcessByStdio<null, null, null>;
|
778 | function spawn(command: string, options: SpawnOptions): ChildProcess;
|
779 | // overloads of spawn with 'args'
|
780 | function spawn(command: string, args?: ReadonlyArray<string>, options?: SpawnOptionsWithoutStdio): ChildProcessWithoutNullStreams;
|
781 | function spawn(command: string, args: ReadonlyArray<string>, options: SpawnOptionsWithStdioTuple<StdioPipe, StdioPipe, StdioPipe>): ChildProcessByStdio<Writable, Readable, Readable>;
|
782 | function spawn(command: string, args: ReadonlyArray<string>, options: SpawnOptionsWithStdioTuple<StdioPipe, StdioPipe, StdioNull>): ChildProcessByStdio<Writable, Readable, null>;
|
783 | function spawn(command: string, args: ReadonlyArray<string>, options: SpawnOptionsWithStdioTuple<StdioPipe, StdioNull, StdioPipe>): ChildProcessByStdio<Writable, null, Readable>;
|
784 | function spawn(command: string, args: ReadonlyArray<string>, options: SpawnOptionsWithStdioTuple<StdioNull, StdioPipe, StdioPipe>): ChildProcessByStdio<null, Readable, Readable>;
|
785 | function spawn(command: string, args: ReadonlyArray<string>, options: SpawnOptionsWithStdioTuple<StdioPipe, StdioNull, StdioNull>): ChildProcessByStdio<Writable, null, null>;
|
786 | function spawn(command: string, args: ReadonlyArray<string>, options: SpawnOptionsWithStdioTuple<StdioNull, StdioPipe, StdioNull>): ChildProcessByStdio<null, Readable, null>;
|
787 | function spawn(command: string, args: ReadonlyArray<string>, options: SpawnOptionsWithStdioTuple<StdioNull, StdioNull, StdioPipe>): ChildProcessByStdio<null, null, Readable>;
|
788 | function spawn(command: string, args: ReadonlyArray<string>, options: SpawnOptionsWithStdioTuple<StdioNull, StdioNull, StdioNull>): ChildProcessByStdio<null, null, null>;
|
789 | function spawn(command: string, args: ReadonlyArray<string>, options: SpawnOptions): ChildProcess;
|
790 | interface ExecOptions extends CommonOptions {
|
791 | shell?: string | undefined;
|
792 | signal?: AbortSignal | undefined;
|
793 | maxBuffer?: number | undefined;
|
794 | killSignal?: NodeJS.Signals | number | undefined;
|
795 | }
|
796 | interface ExecOptionsWithStringEncoding extends ExecOptions {
|
797 | encoding: BufferEncoding;
|
798 | }
|
799 | interface ExecOptionsWithBufferEncoding extends ExecOptions {
|
800 | encoding: BufferEncoding | null; // specify `null`.
|
801 | }
|
802 | interface ExecException extends Error {
|
803 | cmd?: string | undefined;
|
804 | killed?: boolean | undefined;
|
805 | code?: number | undefined;
|
806 | signal?: NodeJS.Signals | undefined;
|
807 | }
|
808 | /**
|
809 | * Spawns a shell then executes the `command` within that shell, buffering any
|
810 | * generated output. The `command` string passed to the exec function is processed
|
811 | * directly by the shell and special characters (vary based on [shell](https://en.wikipedia.org/wiki/List_of_command-line_interpreters))
|
812 | * need to be dealt with accordingly:
|
813 | *
|
814 | * ```js
|
815 | * const { exec } = require('child_process');
|
816 | *
|
817 | * exec('"/path/to/test file/test.sh" arg1 arg2');
|
818 | * // Double quotes are used so that the space in the path is not interpreted as
|
819 | * // a delimiter of multiple arguments.
|
820 | *
|
821 | * exec('echo "The \\$HOME variable is $HOME"');
|
822 | * // The $HOME variable is escaped in the first instance, but not in the second.
|
823 | * ```
|
824 | *
|
825 | * **Never pass unsanitized user input to this function. Any input containing shell**
|
826 | * **metacharacters may be used to trigger arbitrary command execution.**
|
827 | *
|
828 | * 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
|
829 | * `error.code` property will be
|
830 | * 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
|
831 | * process.
|
832 | *
|
833 | * The `stdout` and `stderr` arguments passed to the callback will contain the
|
834 | * stdout and stderr output of the child process. By default, Node.js will decode
|
835 | * the output as UTF-8 and pass strings to the callback. The `encoding` option
|
836 | * can be used to specify the character encoding used to decode the stdout and
|
837 | * stderr output. If `encoding` is `'buffer'`, or an unrecognized character
|
838 | * encoding, `Buffer` objects will be passed to the callback instead.
|
839 | *
|
840 | * ```js
|
841 | * const { exec } = require('child_process');
|
842 | * exec('cat *.js missing_file | wc -l', (error, stdout, stderr) => {
|
843 | * if (error) {
|
844 | * console.error(`exec error: ${error}`);
|
845 | * return;
|
846 | * }
|
847 | * console.log(`stdout: ${stdout}`);
|
848 | * console.error(`stderr: ${stderr}`);
|
849 | * });
|
850 | * ```
|
851 | *
|
852 | * If `timeout` is greater than `0`, the parent will send the signal
|
853 | * identified by the `killSignal` property (the default is `'SIGTERM'`) if the
|
854 | * child runs longer than `timeout` milliseconds.
|
855 | *
|
856 | * Unlike the [`exec(3)`](http://man7.org/linux/man-pages/man3/exec.3.html) POSIX system call, `child_process.exec()` does not replace
|
857 | * the existing process and uses a shell to execute the command.
|
858 | *
|
859 | * If this method is invoked as its `util.promisify()` ed version, it returns
|
860 | * a `Promise` for an `Object` with `stdout` and `stderr` properties. The returned`ChildProcess` instance is attached to the `Promise` as a `child` property. In
|
861 | * case of an error (including any error resulting in an exit code other than 0), a
|
862 | * rejected promise is returned, with the same `error` object given in the
|
863 | * callback, but with two additional properties `stdout` and `stderr`.
|
864 | *
|
865 | * ```js
|
866 | * const util = require('util');
|
867 | * const exec = util.promisify(require('child_process').exec);
|
868 | *
|
869 | * async function lsExample() {
|
870 | * const { stdout, stderr } = await exec('ls');
|
871 | * console.log('stdout:', stdout);
|
872 | * console.error('stderr:', stderr);
|
873 | * }
|
874 | * lsExample();
|
875 | * ```
|
876 | *
|
877 | * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.kill()` on the child process except
|
878 | * the error passed to the callback will be an `AbortError`:
|
879 | *
|
880 | * ```js
|
881 | * const { exec } = require('child_process');
|
882 | * const controller = new AbortController();
|
883 | * const { signal } = controller;
|
884 | * const child = exec('grep ssh', { signal }, (error) => {
|
885 | * console.log(error); // an AbortError
|
886 | * });
|
887 | * controller.abort();
|
888 | * ```
|
889 | * @since v0.1.90
|
890 | * @param command The command to run, with space-separated arguments.
|
891 | * @param callback called with the output when process terminates.
|
892 | */
|
893 | function exec(command: string, callback?: (error: ExecException | null, stdout: string, stderr: string) => void): ChildProcess;
|
894 | // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`.
|
895 | function exec(
|
896 | command: string,
|
897 | options: {
|
898 | encoding: 'buffer' | null;
|
899 | } & ExecOptions,
|
900 | callback?: (error: ExecException | null, stdout: Buffer, stderr: Buffer) => void
|
901 | ): ChildProcess;
|
902 | // `options` with well known `encoding` means stdout/stderr are definitely `string`.
|
903 | function exec(
|
904 | command: string,
|
905 | options: {
|
906 | encoding: BufferEncoding;
|
907 | } & ExecOptions,
|
908 | callback?: (error: ExecException | null, stdout: string, stderr: string) => void
|
909 | ): ChildProcess;
|
910 | // `options` with an `encoding` whose type is `string` means stdout/stderr could either be `Buffer` or `string`.
|
911 | // There is no guarantee the `encoding` is unknown as `string` is a superset of `BufferEncoding`.
|
912 | function exec(
|
913 | command: string,
|
914 | options: {
|
915 | encoding: BufferEncoding;
|
916 | } & ExecOptions,
|
917 | callback?: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void
|
918 | ): ChildProcess;
|
919 | // `options` without an `encoding` means stdout/stderr are definitely `string`.
|
920 | function exec(command: string, options: ExecOptions, callback?: (error: ExecException | null, stdout: string, stderr: string) => void): ChildProcess;
|
921 | // fallback if nothing else matches. Worst case is always `string | Buffer`.
|
922 | function exec(
|
923 | command: string,
|
924 | options: (ObjectEncodingOptions & ExecOptions) | undefined | null,
|
925 | callback?: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void
|
926 | ): ChildProcess;
|
927 | interface PromiseWithChild<T> extends Promise<T> {
|
928 | child: ChildProcess;
|
929 | }
|
930 | namespace exec {
|
931 | function __promisify__(command: string): PromiseWithChild<{
|
932 | stdout: string;
|
933 | stderr: string;
|
934 | }>;
|
935 | function __promisify__(
|
936 | command: string,
|
937 | options: {
|
938 | encoding: 'buffer' | null;
|
939 | } & ExecOptions
|
940 | ): PromiseWithChild<{
|
941 | stdout: Buffer;
|
942 | stderr: Buffer;
|
943 | }>;
|
944 | function __promisify__(
|
945 | command: string,
|
946 | options: {
|
947 | encoding: BufferEncoding;
|
948 | } & ExecOptions
|
949 | ): PromiseWithChild<{
|
950 | stdout: string;
|
951 | stderr: string;
|
952 | }>;
|
953 | function __promisify__(
|
954 | command: string,
|
955 | options: ExecOptions
|
956 | ): PromiseWithChild<{
|
957 | stdout: string;
|
958 | stderr: string;
|
959 | }>;
|
960 | function __promisify__(
|
961 | command: string,
|
962 | options?: (ObjectEncodingOptions & ExecOptions) | null
|
963 | ): PromiseWithChild<{
|
964 | stdout: string | Buffer;
|
965 | stderr: string | Buffer;
|
966 | }>;
|
967 | }
|
968 | interface ExecFileOptions extends CommonOptions, Abortable {
|
969 | maxBuffer?: number | undefined;
|
970 | killSignal?: NodeJS.Signals | number | undefined;
|
971 | windowsVerbatimArguments?: boolean | undefined;
|
972 | shell?: boolean | string | undefined;
|
973 | signal?: AbortSignal | undefined;
|
974 | }
|
975 | interface ExecFileOptionsWithStringEncoding extends ExecFileOptions {
|
976 | encoding: BufferEncoding;
|
977 | }
|
978 | interface ExecFileOptionsWithBufferEncoding extends ExecFileOptions {
|
979 | encoding: 'buffer' | null;
|
980 | }
|
981 | interface ExecFileOptionsWithOtherEncoding extends ExecFileOptions {
|
982 | encoding: BufferEncoding;
|
983 | }
|
984 | type ExecFileException = ExecException & NodeJS.ErrnoException;
|
985 | /**
|
986 | * The `child_process.execFile()` function is similar to {@link exec} except that it does not spawn a shell by default. Rather, the specified
|
987 | * executable `file` is spawned directly as a new process making it slightly more
|
988 | * efficient than {@link exec}.
|
989 | *
|
990 | * The same options as {@link exec} are supported. Since a shell is
|
991 | * not spawned, behaviors such as I/O redirection and file globbing are not
|
992 | * supported.
|
993 | *
|
994 | * ```js
|
995 | * const { execFile } = require('child_process');
|
996 | * const child = execFile('node', ['--version'], (error, stdout, stderr) => {
|
997 | * if (error) {
|
998 | * throw error;
|
999 | * }
|
1000 | * console.log(stdout);
|
1001 | * });
|
1002 | * ```
|
1003 | *
|
1004 | * The `stdout` and `stderr` arguments passed to the callback will contain the
|
1005 | * stdout and stderr output of the child process. By default, Node.js will decode
|
1006 | * the output as UTF-8 and pass strings to the callback. The `encoding` option
|
1007 | * can be used to specify the character encoding used to decode the stdout and
|
1008 | * stderr output. If `encoding` is `'buffer'`, or an unrecognized character
|
1009 | * encoding, `Buffer` objects will be passed to the callback instead.
|
1010 | *
|
1011 | * If this method is invoked as its `util.promisify()` ed version, it returns
|
1012 | * a `Promise` for an `Object` with `stdout` and `stderr` properties. The returned`ChildProcess` instance is attached to the `Promise` as a `child` property. In
|
1013 | * case of an error (including any error resulting in an exit code other than 0), a
|
1014 | * rejected promise is returned, with the same `error` object given in the
|
1015 | * callback, but with two additional properties `stdout` and `stderr`.
|
1016 | *
|
1017 | * ```js
|
1018 | * const util = require('util');
|
1019 | * const execFile = util.promisify(require('child_process').execFile);
|
1020 | * async function getVersion() {
|
1021 | * const { stdout } = await execFile('node', ['--version']);
|
1022 | * console.log(stdout);
|
1023 | * }
|
1024 | * getVersion();
|
1025 | * ```
|
1026 | *
|
1027 | * **If the `shell` option is enabled, do not pass unsanitized user input to this**
|
1028 | * **function. Any input containing shell metacharacters may be used to trigger**
|
1029 | * **arbitrary command execution.**
|
1030 | *
|
1031 | * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.kill()` on the child process except
|
1032 | * the error passed to the callback will be an `AbortError`:
|
1033 | *
|
1034 | * ```js
|
1035 | * const { execFile } = require('child_process');
|
1036 | * const controller = new AbortController();
|
1037 | * const { signal } = controller;
|
1038 | * const child = execFile('node', ['--version'], { signal }, (error) => {
|
1039 | * console.log(error); // an AbortError
|
1040 | * });
|
1041 | * controller.abort();
|
1042 | * ```
|
1043 | * @since v0.1.91
|
1044 | * @param file The name or path of the executable file to run.
|
1045 | * @param args List of string arguments.
|
1046 | * @param callback Called with the output when process terminates.
|
1047 | */
|
1048 | function execFile(file: string): ChildProcess;
|
1049 | function execFile(file: string, options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null): ChildProcess;
|
1050 | function execFile(file: string, args?: ReadonlyArray<string> | null): ChildProcess;
|
1051 | function execFile(file: string, args: ReadonlyArray<string> | undefined | null, options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null): ChildProcess;
|
1052 | // no `options` definitely means stdout/stderr are `string`.
|
1053 | function execFile(file: string, callback: (error: ExecFileException | null, stdout: string, stderr: string) => void): ChildProcess;
|
1054 | function execFile(file: string, args: ReadonlyArray<string> | undefined | null, callback: (error: ExecFileException | null, stdout: string, stderr: string) => void): ChildProcess;
|
1055 | // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`.
|
1056 | function execFile(file: string, options: ExecFileOptionsWithBufferEncoding, callback: (error: ExecFileException | null, stdout: Buffer, stderr: Buffer) => void): ChildProcess;
|
1057 | function execFile(
|
1058 | file: string,
|
1059 | args: ReadonlyArray<string> | undefined | null,
|
1060 | options: ExecFileOptionsWithBufferEncoding,
|
1061 | callback: (error: ExecFileException | null, stdout: Buffer, stderr: Buffer) => void
|
1062 | ): ChildProcess;
|
1063 | // `options` with well known `encoding` means stdout/stderr are definitely `string`.
|
1064 | function execFile(file: string, options: ExecFileOptionsWithStringEncoding, callback: (error: ExecFileException | null, stdout: string, stderr: string) => void): ChildProcess;
|
1065 | function execFile(
|
1066 | file: string,
|
1067 | args: ReadonlyArray<string> | undefined | null,
|
1068 | options: ExecFileOptionsWithStringEncoding,
|
1069 | callback: (error: ExecFileException | null, stdout: string, stderr: string) => void
|
1070 | ): ChildProcess;
|
1071 | // `options` with an `encoding` whose type is `string` means stdout/stderr could either be `Buffer` or `string`.
|
1072 | // There is no guarantee the `encoding` is unknown as `string` is a superset of `BufferEncoding`.
|
1073 | function execFile(file: string, options: ExecFileOptionsWithOtherEncoding, callback: (error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void): ChildProcess;
|
1074 | function execFile(
|
1075 | file: string,
|
1076 | args: ReadonlyArray<string> | undefined | null,
|
1077 | options: ExecFileOptionsWithOtherEncoding,
|
1078 | callback: (error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void
|
1079 | ): ChildProcess;
|
1080 | // `options` without an `encoding` means stdout/stderr are definitely `string`.
|
1081 | function execFile(file: string, options: ExecFileOptions, callback: (error: ExecFileException | null, stdout: string, stderr: string) => void): ChildProcess;
|
1082 | function execFile(
|
1083 | file: string,
|
1084 | args: ReadonlyArray<string> | undefined | null,
|
1085 | options: ExecFileOptions,
|
1086 | callback: (error: ExecFileException | null, stdout: string, stderr: string) => void
|
1087 | ): ChildProcess;
|
1088 | // fallback if nothing else matches. Worst case is always `string | Buffer`.
|
1089 | function execFile(
|
1090 | file: string,
|
1091 | options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null,
|
1092 | callback: ((error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void) | undefined | null
|
1093 | ): ChildProcess;
|
1094 | function execFile(
|
1095 | file: string,
|
1096 | args: ReadonlyArray<string> | undefined | null,
|
1097 | options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null,
|
1098 | callback: ((error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void) | undefined | null
|
1099 | ): ChildProcess;
|
1100 | namespace execFile {
|
1101 | function __promisify__(file: string): PromiseWithChild<{
|
1102 | stdout: string;
|
1103 | stderr: string;
|
1104 | }>;
|
1105 | function __promisify__(
|
1106 | file: string,
|
1107 | args: ReadonlyArray<string> | undefined | null
|
1108 | ): PromiseWithChild<{
|
1109 | stdout: string;
|
1110 | stderr: string;
|
1111 | }>;
|
1112 | function __promisify__(
|
1113 | file: string,
|
1114 | options: ExecFileOptionsWithBufferEncoding
|
1115 | ): PromiseWithChild<{
|
1116 | stdout: Buffer;
|
1117 | stderr: Buffer;
|
1118 | }>;
|
1119 | function __promisify__(
|
1120 | file: string,
|
1121 | args: ReadonlyArray<string> | undefined | null,
|
1122 | options: ExecFileOptionsWithBufferEncoding
|
1123 | ): PromiseWithChild<{
|
1124 | stdout: Buffer;
|
1125 | stderr: Buffer;
|
1126 | }>;
|
1127 | function __promisify__(
|
1128 | file: string,
|
1129 | options: ExecFileOptionsWithStringEncoding
|
1130 | ): PromiseWithChild<{
|
1131 | stdout: string;
|
1132 | stderr: string;
|
1133 | }>;
|
1134 | function __promisify__(
|
1135 | file: string,
|
1136 | args: ReadonlyArray<string> | undefined | null,
|
1137 | options: ExecFileOptionsWithStringEncoding
|
1138 | ): PromiseWithChild<{
|
1139 | stdout: string;
|
1140 | stderr: string;
|
1141 | }>;
|
1142 | function __promisify__(
|
1143 | file: string,
|
1144 | options: ExecFileOptionsWithOtherEncoding
|
1145 | ): PromiseWithChild<{
|
1146 | stdout: string | Buffer;
|
1147 | stderr: string | Buffer;
|
1148 | }>;
|
1149 | function __promisify__(
|
1150 | file: string,
|
1151 | args: ReadonlyArray<string> | undefined | null,
|
1152 | options: ExecFileOptionsWithOtherEncoding
|
1153 | ): PromiseWithChild<{
|
1154 | stdout: string | Buffer;
|
1155 | stderr: string | Buffer;
|
1156 | }>;
|
1157 | function __promisify__(
|
1158 | file: string,
|
1159 | options: ExecFileOptions
|
1160 | ): PromiseWithChild<{
|
1161 | stdout: string;
|
1162 | stderr: string;
|
1163 | }>;
|
1164 | function __promisify__(
|
1165 | file: string,
|
1166 | args: ReadonlyArray<string> | undefined | null,
|
1167 | options: ExecFileOptions
|
1168 | ): PromiseWithChild<{
|
1169 | stdout: string;
|
1170 | stderr: string;
|
1171 | }>;
|
1172 | function __promisify__(
|
1173 | file: string,
|
1174 | options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null
|
1175 | ): PromiseWithChild<{
|
1176 | stdout: string | Buffer;
|
1177 | stderr: string | Buffer;
|
1178 | }>;
|
1179 | function __promisify__(
|
1180 | file: string,
|
1181 | args: ReadonlyArray<string> | undefined | null,
|
1182 | options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null
|
1183 | ): PromiseWithChild<{
|
1184 | stdout: string | Buffer;
|
1185 | stderr: string | Buffer;
|
1186 | }>;
|
1187 | }
|
1188 | interface ForkOptions extends ProcessEnvOptions, MessagingOptions, Abortable {
|
1189 | execPath?: string | undefined;
|
1190 | execArgv?: string[] | undefined;
|
1191 | silent?: boolean | undefined;
|
1192 | stdio?: StdioOptions | undefined;
|
1193 | detached?: boolean | undefined;
|
1194 | windowsVerbatimArguments?: boolean | undefined;
|
1195 | }
|
1196 | /**
|
1197 | * The `child_process.fork()` method is a special case of {@link spawn} used specifically to spawn new Node.js processes.
|
1198 | * Like {@link spawn}, a `ChildProcess` object is returned. The
|
1199 | * returned `ChildProcess` will have an additional communication channel
|
1200 | * built-in that allows messages to be passed back and forth between the parent and
|
1201 | * child. See `subprocess.send()` for details.
|
1202 | *
|
1203 | * Keep in mind that spawned Node.js child processes are
|
1204 | * independent of the parent with exception of the IPC communication channel
|
1205 | * that is established between the two. Each process has its own memory, with
|
1206 | * their own V8 instances. Because of the additional resource allocations
|
1207 | * required, spawning a large number of child Node.js processes is not
|
1208 | * recommended.
|
1209 | *
|
1210 | * 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
|
1211 | * execution path to be used.
|
1212 | *
|
1213 | * Node.js processes launched with a custom `execPath` will communicate with the
|
1214 | * parent process using the file descriptor (fd) identified using the
|
1215 | * environment variable `NODE_CHANNEL_FD` on the child process.
|
1216 | *
|
1217 | * Unlike the [`fork(2)`](http://man7.org/linux/man-pages/man2/fork.2.html) POSIX system call, `child_process.fork()` does not clone the
|
1218 | * current process.
|
1219 | *
|
1220 | * The `shell` option available in {@link spawn} is not supported by`child_process.fork()` and will be ignored if set.
|
1221 | *
|
1222 | * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.kill()` on the child process except
|
1223 | * the error passed to the callback will be an `AbortError`:
|
1224 | *
|
1225 | * ```js
|
1226 | * if (process.argv[2] === 'child') {
|
1227 | * setTimeout(() => {
|
1228 | * console.log(`Hello from ${process.argv[2]}!`);
|
1229 | * }, 1_000);
|
1230 | * } else {
|
1231 | * const { fork } = require('child_process');
|
1232 | * const controller = new AbortController();
|
1233 | * const { signal } = controller;
|
1234 | * const child = fork(__filename, ['child'], { signal });
|
1235 | * child.on('error', (err) => {
|
1236 | * // This will be called with err being an AbortError if the controller aborts
|
1237 | * });
|
1238 | * controller.abort(); // Stops the child process
|
1239 | * }
|
1240 | * ```
|
1241 | * @since v0.5.0
|
1242 | * @param modulePath The module to run in the child.
|
1243 | * @param args List of string arguments.
|
1244 | */
|
1245 | function fork(modulePath: string, options?: ForkOptions): ChildProcess;
|
1246 | function fork(modulePath: string, args?: ReadonlyArray<string>, options?: ForkOptions): ChildProcess;
|
1247 | interface SpawnSyncOptions extends CommonSpawnOptions {
|
1248 | input?: string | NodeJS.ArrayBufferView | undefined;
|
1249 | maxBuffer?: number | undefined;
|
1250 | encoding?: BufferEncoding | 'buffer' | null | undefined;
|
1251 | }
|
1252 | interface SpawnSyncOptionsWithStringEncoding extends SpawnSyncOptions {
|
1253 | encoding: BufferEncoding;
|
1254 | }
|
1255 | interface SpawnSyncOptionsWithBufferEncoding extends SpawnSyncOptions {
|
1256 | encoding?: 'buffer' | null | undefined;
|
1257 | }
|
1258 | interface SpawnSyncReturns<T> {
|
1259 | pid: number;
|
1260 | output: Array<T | null>;
|
1261 | stdout: T;
|
1262 | stderr: T;
|
1263 | status: number | null;
|
1264 | signal: NodeJS.Signals | null;
|
1265 | error?: Error | undefined;
|
1266 | }
|
1267 | /**
|
1268 | * The `child_process.spawnSync()` method is generally identical to {@link spawn} with the exception that the function will not return
|
1269 | * until the child process has fully closed. When a timeout has been encountered
|
1270 | * and `killSignal` is sent, the method won't return until the process has
|
1271 | * completely exited. If the process intercepts and handles the `SIGTERM` signal
|
1272 | * and doesn't exit, the parent process will wait until the child process has
|
1273 | * exited.
|
1274 | *
|
1275 | * **If the `shell` option is enabled, do not pass unsanitized user input to this**
|
1276 | * **function. Any input containing shell metacharacters may be used to trigger**
|
1277 | * **arbitrary command execution.**
|
1278 | * @since v0.11.12
|
1279 | * @param command The command to run.
|
1280 | * @param args List of string arguments.
|
1281 | */
|
1282 | function spawnSync(command: string): SpawnSyncReturns<Buffer>;
|
1283 | function spawnSync(command: string, options: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns<string>;
|
1284 | function spawnSync(command: string, options: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns<Buffer>;
|
1285 | function spawnSync(command: string, options?: SpawnSyncOptions): SpawnSyncReturns<string | Buffer>;
|
1286 | function spawnSync(command: string, args: ReadonlyArray<string>): SpawnSyncReturns<Buffer>;
|
1287 | function spawnSync(command: string, args: ReadonlyArray<string>, options: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns<string>;
|
1288 | function spawnSync(command: string, args: ReadonlyArray<string>, options: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns<Buffer>;
|
1289 | function spawnSync(command: string, args?: ReadonlyArray<string>, options?: SpawnSyncOptions): SpawnSyncReturns<string | Buffer>;
|
1290 | interface CommonExecOptions extends CommonOptions {
|
1291 | input?: string | NodeJS.ArrayBufferView | undefined;
|
1292 | stdio?: StdioOptions | undefined;
|
1293 | killSignal?: NodeJS.Signals | number | undefined;
|
1294 | maxBuffer?: number | undefined;
|
1295 | encoding?: BufferEncoding | 'buffer' | null | undefined;
|
1296 | }
|
1297 | interface ExecSyncOptions extends CommonExecOptions {
|
1298 | shell?: string | undefined;
|
1299 | }
|
1300 | interface ExecSyncOptionsWithStringEncoding extends ExecSyncOptions {
|
1301 | encoding: BufferEncoding;
|
1302 | }
|
1303 | interface ExecSyncOptionsWithBufferEncoding extends ExecSyncOptions {
|
1304 | encoding?: 'buffer' | null | undefined;
|
1305 | }
|
1306 | /**
|
1307 | * The `child_process.execSync()` method is generally identical to {@link exec} with the exception that the method will not return
|
1308 | * until the child process has fully closed. When a timeout has been encountered
|
1309 | * and `killSignal` is sent, the method won't return until the process has
|
1310 | * 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
|
1311 | * has exited.
|
1312 | *
|
1313 | * If the process times out or has a non-zero exit code, this method will throw.
|
1314 | * The `Error` object will contain the entire result from {@link spawnSync}.
|
1315 | *
|
1316 | * **Never pass unsanitized user input to this function. Any input containing shell**
|
1317 | * **metacharacters may be used to trigger arbitrary command execution.**
|
1318 | * @since v0.11.12
|
1319 | * @param command The command to run.
|
1320 | * @return The stdout from the command.
|
1321 | */
|
1322 | function execSync(command: string): Buffer;
|
1323 | function execSync(command: string, options: ExecSyncOptionsWithStringEncoding): string;
|
1324 | function execSync(command: string, options: ExecSyncOptionsWithBufferEncoding): Buffer;
|
1325 | function execSync(command: string, options?: ExecSyncOptions): string | Buffer;
|
1326 | interface ExecFileSyncOptions extends CommonExecOptions {
|
1327 | shell?: boolean | string | undefined;
|
1328 | }
|
1329 | interface ExecFileSyncOptionsWithStringEncoding extends ExecFileSyncOptions {
|
1330 | encoding: BufferEncoding;
|
1331 | }
|
1332 | interface ExecFileSyncOptionsWithBufferEncoding extends ExecFileSyncOptions {
|
1333 | encoding?: 'buffer' | null; // specify `null`.
|
1334 | }
|
1335 | /**
|
1336 | * The `child_process.execFileSync()` method is generally identical to {@link execFile} with the exception that the method will not
|
1337 | * return until the child process has fully closed. When a timeout has been
|
1338 | * encountered and `killSignal` is sent, the method won't return until the process
|
1339 | * has completely exited.
|
1340 | *
|
1341 | * If the child process intercepts and handles the `SIGTERM` signal and
|
1342 | * does not exit, the parent process will still wait until the child process has
|
1343 | * exited.
|
1344 | *
|
1345 | * 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}.
|
1346 | *
|
1347 | * **If the `shell` option is enabled, do not pass unsanitized user input to this**
|
1348 | * **function. Any input containing shell metacharacters may be used to trigger**
|
1349 | * **arbitrary command execution.**
|
1350 | * @since v0.11.12
|
1351 | * @param file The name or path of the executable file to run.
|
1352 | * @param args List of string arguments.
|
1353 | * @return The stdout from the command.
|
1354 | */
|
1355 | function execFileSync(file: string): Buffer;
|
1356 | function execFileSync(file: string, options: ExecFileSyncOptionsWithStringEncoding): string;
|
1357 | function execFileSync(file: string, options: ExecFileSyncOptionsWithBufferEncoding): Buffer;
|
1358 | function execFileSync(file: string, options?: ExecFileSyncOptions): string | Buffer;
|
1359 | function execFileSync(file: string, args: ReadonlyArray<string>): Buffer;
|
1360 | function execFileSync(file: string, args: ReadonlyArray<string>, options: ExecFileSyncOptionsWithStringEncoding): string;
|
1361 | function execFileSync(file: string, args: ReadonlyArray<string>, options: ExecFileSyncOptionsWithBufferEncoding): Buffer;
|
1362 | function execFileSync(file: string, args?: ReadonlyArray<string>, options?: ExecFileSyncOptions): string | Buffer;
|
1363 | }
|
1364 | declare module 'node:child_process' {
|
1365 | export * from 'child_process';
|
1366 | }
|