node.js多进程
Node.js provides a child_process
module that provides the ability to spawn child processes.
Node.js提供了child_process
模块,该模块提供了生成子进程的功能。
Require the module, and get the spawn
function from it:
需要模块,并从中获取spawn
函数:
const { spawn } = require('child_process')
then you can call spawn()
passing 2 parameters.
那么您可以通过两个参数调用spawn()
。
The first parameter is the command to run.
第一个参数是要运行的命令。
The second parameter is an array containing a list of options.
第二个参数是一个包含选项列表的数组。
Here’s an example:
这是一个例子:
spawn('ls', ['-lh', 'test'])
In this case you run the ls
command with 2 options: -lh
and test
. This results in the command ls -lh test
, which (given that the test
file exists in the same folder you run this command in), results in the details about the file:
在这种情况下,您可以使用以下两个选项运行ls
命令: -lh
和test
。 这将导致命令ls -lh test
,(假设test
文件位于您运行此命令的同一文件夹中),将导致有关该文件的详细信息:
-rw-r--r-- 1 flaviocopes staff 6B Sep 25 09:57 test
The result of the spawn()
function call is an instance of the ChildProcess
class that identifies the spawned child process.
spawn()
函数调用的结果是ChildProcess
类的实例,该类标识了生成的子进程。
Here’s a slightly more complicated example, fully working. We watch the test
file and whenever it’s changed, we run the ls -lh
command on it:
这是一个稍微复杂的示例,可以正常工作。 我们观察test
文件,并在更改文件时在其上运行ls -lh
命令:
'use strict'
const fs = require('fs')
const { spawn } = require('child_process')
const filename = 'test'
fs.watch(filename, () => {
const ls = spawn('ls', ['-lh', filename])
})
There’s one thing missing. We must pipe the output from the child process to the main process, otherwise we won’t see any output from it.
缺少一件事。 我们必须将子进程的输出通过管道传递给主进程,否则我们将看不到任何输出。
We do so by calling the pipe()
method on the stdout
property of the child process:
stdout
,我们在子进程的stdout
属性上调用pipe()
方法:
'use strict'
const fs = require('fs')
const { spawn } = require('child_process')
const filename = 'test'
fs.watch(filename, () => {
const ls = spawn('ls', ['-lh', filename])
ls.stdout.pipe(process.stdout)
})
翻译自: https://flaviocopes.com/how-to-spawn-child-process-node/
node.js多进程