- Node.js Child Process — Создание и работа с дочерними процессами в Node
- Метод child_process.exec()
- Метод child_process.spawn()
- Метод child_process.fork()
- Метод child_process.send()
- Node.js v15.14.0 documentation
- Child process #
- Asynchronous process creation #
- Spawning .bat and .cmd files on Windows #
- child_process.exec(command[, options][, callback]) #
- child_process.execFile(file[, args][, options][, callback]) #
- child_process.fork(modulePath[, args][, options]) #
- child_process.spawn(command[, args][, options]) #
- Synchronous process creation #
- child_process.execFileSync(file[, args][, options]) #
- child_process.execSync(command[, options]) #
- child_process.spawnSync(command[, args][, options]) #
- Class: ChildProcess #
- Event: ‘close’ #
- Event: ‘disconnect’ #
- Event: ‘error’ #
- Event: ‘exit’ #
- Event: ‘message’ #
- Event: ‘spawn’ #
- subprocess.channel #
- subprocess.connected #
- subprocess.disconnect() #
- subprocess.exitCode #
- subprocess.kill([signal]) #
- subprocess.killed #
- subprocess.pid #
- subprocess.ref() #
- subprocess.send(message[, sendHandle[, options]][, callback]) #
- subprocess.signalCode #
- subprocess.spawnargs #
- subprocess.spawnfile #
- subprocess.stderr #
- subprocess.stdin #
- subprocess.stdio #
- subprocess.stdout #
- subprocess.unref() #
- maxBuffer and Unicode #
- Shell requirements #
- Default Windows shell #
- Advanced serialization #
Node.js Child Process — Создание и работа с дочерними процессами в Node
Child Process — это модуль в Node.js, который можно подключить с помощью функции require(). Используя модуль child_process мы можем полноценно использовать функционал процессов. Ниже перечислены некоторые возможности модуля:
- С помощью модуля child_process мы можем запускать команды shell. Shell — это командный язык высокого уровня, который используется в Unix как интерпретатор. Он совместим с Bash. С помощью простых Shell команд мы можем управлять сервером и написать сложные сценарий.
- Модуль child_process позволяет запускать параллельные дочерние процессы.
- Модуль child_process позволяет обмениваться сообщениями между собой.
Модуль имеет несколько простых но очень важных методов, которые облегчают жизнь.
Метод child_process.exec()
С помощью метода child_process.exec() мы можем запускать команды на выполнения. После выполнения результат будет сохранен в буфере.
Пример использование метода child_process.exec():
Тут мы с помощью метода child_process.exec() запускаем shell-команду cat, выводящую содержимое нескольких файлов и через пайп передающую их команде wc, считывающей количество строк. Вторым аргументом передается массив параметров в данном случае мы изменяем рабочую директорию. Метод в качестве третьего аргумента принимает функцию, который принимает 3 параметра. Первый параметр — это объект ошибки, а второй и третий — это потоки stdout и stderr. Ценность команды состоит в возможности действий с полученными результатами.
Метод child_process.spawn()
Следующий метод — это child_process.spawn(), который запускает команду в новом процессе, дескриптор которого становится доступным:
Здесь все просто — любой вывод исполняемой команды передается в поток stdout дочернего процесса (или stderr, если случилось ошибка), и мы связали обработчики именно с этими объектами. Мы видим, что поток выполняется параллельно с основным процессом и завершается с кодом 0, что свидетельствует об успехе.
Метод child_process.fork()
Следующий метод — это child_process.fork(), который запускает дочерним процессом новый процесс, порожденный самой Node.js. Ниже представлен простой пример работы данного метода:
Тут мы запускаем два дочерних процесса, исполняющих код, характеризующихся в файлах sub1.js и sub2.js, и создаем бесконечный цикл вывода сообщений. Ниже представлен содержимое дочерних процессов:
sub1.js:
sub2.js:
После запуска основного скрипта мы увидим, что все работает параллельно.
Метод child_process.send()
Последний метод, который будет рассмотрен в этом статье — это метод send() модуля Child Process. Он отсылает сообщения от одного процесса к другому:
main.js:
sub.js:
В виде сообщение также можно посылать команды управления.
Node.js v15.14.0 documentation
Child process #
The child_process module provides the ability to spawn subprocesses in a manner that is similar, but not identical, to popen(3) . This capability is primarily provided by the child_process.spawn() function:
By default, pipes for stdin , stdout , and stderr are established between the parent Node.js process and the spawned subprocess. These pipes have limited (and platform-specific) capacity. If the subprocess writes to stdout in excess of that limit without the output being captured, the subprocess blocks waiting for the pipe buffer to accept more data. This is identical to the behavior of pipes in the shell. Use the < stdio: 'ignore' >option if the output will not be consumed.
The command lookup is performed using the options.env.PATH environment variable if it is in the options object. Otherwise, process.env.PATH is used.
On Windows, environment variables are case-insensitive. Node.js lexicographically sorts the env keys and uses the first one that case-insensitively matches. Only first (in lexicographic order) entry will be passed to the subprocess. This might lead to issues on Windows when passing objects to the env option that have multiple variants of the same key, such as PATH and Path .
The child_process.spawn() method spawns the child process asynchronously, without blocking the Node.js event loop. The child_process.spawnSync() function provides equivalent functionality in a synchronous manner that blocks the event loop until the spawned process either exits or is terminated.
For convenience, the child_process module provides a handful of synchronous and asynchronous alternatives to child_process.spawn() and child_process.spawnSync() . Each of these alternatives are implemented on top of child_process.spawn() or child_process.spawnSync() .
- child_process.exec() : spawns a shell and runs a command within that shell, passing the stdout and stderr to a callback function when complete.
- child_process.execFile() : similar to child_process.exec() except that it spawns the command directly without first spawning a shell by default.
- child_process.fork() : spawns a new Node.js process and invokes a specified module with an IPC communication channel established that allows sending messages between parent and child.
- child_process.execSync() : a synchronous version of child_process.exec() that will block the Node.js event loop.
- child_process.execFileSync() : a synchronous version of child_process.execFile() that will block the Node.js event loop.
For certain use cases, such as automating shell scripts, the synchronous counterparts may be more convenient. In many cases, however, the synchronous methods can have significant impact on performance due to stalling the event loop while spawned processes complete.
Asynchronous process creation #
The child_process.spawn() , child_process.fork() , child_process.exec() , and child_process.execFile() methods all follow the idiomatic asynchronous programming pattern typical of other Node.js APIs.
Each of the methods returns a ChildProcess instance. These objects implement the Node.js EventEmitter API, allowing the parent process to register listener functions that are called when certain events occur during the life cycle of the child process.
The child_process.exec() and child_process.execFile() methods additionally allow for an optional callback function to be specified that is invoked when the child process terminates.
Spawning .bat and .cmd files on Windows #
The importance of the distinction between child_process.exec() and child_process.execFile() can vary based on platform. On Unix-type operating systems (Unix, Linux, macOS) child_process.execFile() can be more efficient because it does not spawn a shell by default. On Windows, however, .bat and .cmd files are not executable on their own without a terminal, and therefore cannot be launched using child_process.execFile() . When running on Windows, .bat and .cmd files can be invoked using child_process.spawn() with the shell option set, with child_process.exec() , or by spawning cmd.exe and passing the .bat or .cmd file as an argument (which is what the shell option and child_process.exec() do). In any case, if the script filename contains spaces it needs to be quoted.
child_process.exec(command[, options][, callback]) #
History
Version | Changes | ||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
v15.4.0 |
Version | Changes | |||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
v15.4.0 |
Version | Changes | ||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
v15.13.0 |
Version | Changes | |||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
v15.13.0 |
Version | Changes | ||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
v15.6.0 |
Version | Changes | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
v10.10.0 |
Version | Changes | ||||||||
---|---|---|---|---|---|---|---|---|---|
v10.10.0 |
Version | Changes | |||||
---|---|---|---|---|---|---|
v10.10.0 |
Version | Changes | ||
---|---|---|---|
v14.0.0 |
Version | Changes |
---|---|
v5.8.0 |