博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
node.js多进程_如何使用Node.js生成子进程
阅读量:2503 次
发布时间:2019-05-11

本文共 1971 字,大约阅读时间需要 6 分钟。

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命令: -lhtest 。 这将导致命令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)})

翻译自:

node.js多进程

转载地址:http://olqgb.baihongyu.com/

你可能感兴趣的文章
HTTP协议
查看>>
HTTPS
查看>>
git add . git add -u git add -A区别
查看>>
apache下虚拟域名配置
查看>>
session和cookie区别与联系
查看>>
PHP 实现笛卡尔积
查看>>
Laravel中的$loop
查看>>
CentOS7 重置root密码
查看>>
Centos安装Python3
查看>>
PHP批量插入
查看>>
laravel连接sql server 2008
查看>>
Laravel框架学习笔记之任务调度(定时任务)
查看>>
laravel 定时任务秒级执行
查看>>
浅析 Laravel 官方文档推荐的 Nginx 配置
查看>>
Swagger在Laravel项目中的使用
查看>>
Laravel 的生命周期
查看>>
CentOS Docker 安装
查看>>
Nginx
查看>>
Navicat远程连接云主机数据库
查看>>
Nginx配置文件nginx.conf中文详解(总结)
查看>>