node.js学习笔记(16) child_process(三)

简介:

学习过前两篇笔记的源码分析,再来应用child_process的7个方法就不难理解了。


By default, pipes for stdin, stdout and stderr are established between the parent Node.js process and the spawned child.

默认情况下,Node.js主进程和子进程间就会建立三个管道:stdin、stdout和stderr,即标准输入流、标准输出流和标准错误流。


如今热播的《芈月传》中有一段是秦国七公子之乱,赢华是长子,灭赢华着七公子之乱自然解除。

从child_process“七公子”的源码来看,spawn()是“长子”,既如此,通spawn()则通child_process“七公子”。


知己知彼,百战不殆。先来看看“大公子”spawn()有些什么“本事”。


child_process.spawn(command[, args][, options])#

- command String The command to run 将要运行的命令

- args Array List of string arguments 字符串参数数组

- options Object

-- cwd String Current working directory of the child process 子进程的当前工作目录

-- env Object Environment key-value pairs 环境变量键值对

-- stdio Array|String Child's stdio configuration. (See below)  子进程的stdio配置

-- detached Boolean Prepare child to run independently of its parent process. Specific behavior depends on the platform, see below) 这个子进程的将会变成进程组的领导

-- uid Number Sets the user identity of the process. (See setuid(2).) 设置用户进程的ID

-- gid Number Sets the group identity of the process. (See setgid(2).) 设置进程组的ID

- return: ChildProcess object 


spawn实例


child-process-spawn.js:

const spawn = require('child_process').spawn;
const ls = spawn('ls', ['-lh', '/usr']);

ls.stdout.on('data', function(data){
    console.log('stdout: '+data);
});

ls.stderr.on('data', function(data){
    console.log('stderr: '+data);
});

ls.on('close', function(code){
    console.log('child process exited with code '+code);
});


运行结果:

lee@mypc ~/works/nodejs/study16 $ node child-process-spawn.js 
stdout: total 132K
drwxr-xr-x   2 root root  68K Dec 25 11:18 bin
drwxr-xr-x   2 root root 4.0K Jun 27  2015 games
drwxr-xr-x  40 root root 4.0K Sep 24 16:35 include
drwxr-xr-x 198 root root  24K Dec 25 11:18 lib
drwxr-xr-x  11 root root 4.0K Aug 27 16:31 local
drwxr-xr-x   2 root root  12K Oct 13 10:52 sbin
drwxr-xr-x 326 root root  12K Dec 25 11:18 share
drwxr-xr-x   6 root root 4.0K Jun 27  2015 src

child process exited with code 0

上述实例中,最后三行是监听子进程ls的close事件,当ls关闭时打印code。

除了close事件,child_process还有disconnect、error、exit和message事件,分别是断开、错误、退出和消息。


child_process的这些事件和使用方法,看起来是不是很像events.Emitter,没错,Instances of the ChildProcess class are EventEmitters that represent spawned child processes.


解决了“大公子赢华”,其他“六公子”也就“不足为患”了。

child_process.exec(command[, options][, callback])#


- command String The command to run, with space-separated arguments

- options Object

-- cwd String Current working directory of the child process

-- env Object Environment key-value pairs

-- encoding String (Default: 'utf8')

-- shell String Shell to execute the command with (Default: '/bin/sh' on UNIX, 'cmd.exe' on Windows, The shell should understand the -c switch on UNIX or /s /c on Windows. On Windows, command line parsing should be compatible with cmd.exe.) 字符串,将要执行命令的 Shell(默认: 在 UNIX 中为/bin/sh, 在 Windows 中为cmd.exe, Shell 应当能识别 -c开关在 UNIX 中,或 /s /c 在 Windows 中。 在Windows 中,命令行解析应当能兼容cmd.exe)

-- timeout Number (Default: 0)

-- maxBuffer Number largest amount of data (in bytes) allowed on stdout or stderr - if exceeded child process is killed (Default: 200*1024)  数字, 在 stdout 或 stderr 中允许存在的最大缓冲(二进制),如果超出那么子进程将会被杀死 (默认: 200*1024)

-- killSignal String (Default: 'SIGTERM') 字符串,结束信号(默认:'SIGTERM')

-- uid Number Sets the user identity of the process. (See setuid(2).)

-- gid Number Sets the group identity of the process. (See setgid(2).)

- callback Function called with the output when process terminates

-- error Error

-- stdout Buffer

-- stderr Buffer

- Return: ChildProcess object


child_process.execFile(file[, args][, options][, callback])#


- file String The filename of the program to run

- args Array List of string arguments

- options Object  options同child_process.execFile

-- cwd String Current working directory of the child process

-- env Object Environment key-value pairs

-- encoding String (Default: 'utf8')

-- timeout Number (Default: 0)

-- maxBuffer Number largest amount of data (in bytes) allowed on stdout or stderr - if exceeded child process is killed (Default: 200*1024)

-- killSignal String (Default: 'SIGTERM')

-- uid Number Sets the user identity of the process. (See setuid(2).)

-- gid Number Sets the group identity of the process. (See setgid(2).)

- callback Function called with the output when process terminates

-- error Error

-- stdout Buffer

-- stderr Buffer

- Return: ChildProcess object


child_process.fork(modulePath[, args][, options])#


- modulePath String The module to run in the child 将要在子进程中运行的模块

- args Array List of string arguments

- options Object

-- cwd String Current working directory of the child process

-- env Object Environment key-value pairs

-- execPath String Executable used to create the child process 创建子进程的可执行文件

-- execArgv Array List of string arguments passed to the executable (Default: process.execArgv) 子进程的可执行文件的字符串参数数组(默认: process.execArgv)

-- silent Boolean If true, stdin, stdout, and stderr of the child will be piped to the parent, otherwise they will be inherited from the parent, see the 'pipe' and 'inherit' options for [spawn()][]'s stdio for more details (default is false)  如果为true,子进程的stdin,stdout和stderr将会被关联至父进程,否则,它们将会从父进程中继承。(默认为:false)

-- uid Number Sets the user identity of the process. (See setuid(2).)

-- gid Number Sets the group identity of the process. (See setgid(2).)

- Return: ChildProcess object


child_process.execFileSync(file[, args][, options])#


- file String The filename of the program to run

- args Array List of string arguments

- options Object

-- cwd String Current working directory of the child process

-- input String|Buffer The value which will be passed as stdin to the spawned process

-- supplying this value will override stdio[0]

-- stdio Array Child's stdio configuration. (Default: 'pipe')

-- stderr by default will be output to the parent process' stderr unless stdio is specified

-- env Object Environment key-value pairs

-- uid Number Sets the user identity of the process. (See setuid(2).)

-- gid Number Sets the group identity of the process. (See setgid(2).)

-- timeout Number In milliseconds the maximum amount of time the process is allowed to run. (Default: undefined)

-- killSignal String The signal value to be used when the spawned process will be killed. (Default: 'SIGTERM')

-- maxBuffer Number largest amount of data (in bytes) allowed on stdout or stderr - if exceeded child process is killed

-- encoding String The encoding used for all stdio inputs and outputs. (Default: 'buffer')

- return: Buffer|String The stdout from the command


child_process.execSync(command[, options])#


- command String The command to run

- options Object

-- cwd String Current working directory of the child process

-- input String|Buffer The value which will be passed as stdin to the spawned process

-- supplying this value will override stdio[0]

-- stdio Array Child's stdio configuration. (Default: 'pipe')

-- stderr by default will be output to the parent process' stderr unless stdio is specified

-- env Object Environment key-value pairs

-- shell String Shell to execute the command with (Default: '/bin/sh' on UNIX, 'cmd.exe' on Windows, The shell should understand the -c switch on UNIX or /s /c on Windows. On Windows, command line parsing should be compatible with cmd.exe.)

-- uid Number Sets the user identity of the process. (See setuid(2).)

-- gid Number Sets the group identity of the process. (See setgid(2).)

-- timeout Number In milliseconds the maximum amount of time the process is allowed to run. (Default: undefined)

-- killSignal String The signal value to be used when the spawned process will be killed. (Default: 'SIGTERM')

-- maxBuffer Number largest amount of data (in bytes) allowed on stdout or stderr - if exceeded child process is killed

-- encoding String The encoding used for all stdio inputs and outputs. (Default: 'buffer')

- return: Buffer|String The stdout from the command


child_process.spawnSync(command[, args][, options])#


- command String The command to run

- args Array List of string arguments

- options Object

-- cwd String Current working directory of the child process

-- input String|Buffer The value which will be passed as stdin to the spawned process

-- supplying this value will override stdio[0]

-- stdio Array Child's stdio configuration.

-- env Object Environment key-value pairs

-- uid Number Sets the user identity of the process. (See setuid(2).)

-- gid Number Sets the group identity of the process. (See setgid(2).)

-- timeout Number In milliseconds the maximum amount of time the process is allowed to run. (Default: undefined)

-- killSignal String The signal value to be used when the spawned process will be killed. (Default: 'SIGTERM')

-- maxBuffer Number largest amount of data (in bytes) allowed on stdout or stderr - if exceeded child process is killed

-- encoding String The encoding used for all stdio inputs and outputs. (Default: 'buffer')

- return: Object

-- pid Number Pid of the child process

-- output Array Array of results from stdio output

-- stdout Buffer|String The contents of output[1]

-- stderr Buffer|String The contents of output[2]

-- status Number The exit code of the child process

-- signal String The signal used to kill the child process

-- error Error The error object if the child process failed or timed out

目录
相关文章
|
4天前
|
JavaScript 前端开发 API
Vue学习笔记3:对比纯JavaScript和Vue实现数据更新的实时视图显示
Vue学习笔记3:对比纯JavaScript和Vue实现数据更新的实时视图显示
|
5天前
|
Prometheus 监控 Cloud Native
prometheus学习笔记之node-export
prometheus 监控 node-exporter
|
23天前
|
Web App开发 前端开发 JavaScript
HTML/CSS/JS学习笔记 Day3(HTML--网页标签 下)
HTML/CSS/JS学习笔记 Day3(HTML--网页标签 下)
|
2月前
|
Java jenkins Shell
jenkins学习笔记之五:Maven、Ant、Gradl、Node构建工具集成
jenkins学习笔记之五:Maven、Ant、Gradl、Node构建工具集成
|
3月前
|
JavaScript Java 测试技术
基于springboot+vue.js+uniapp的云的学习笔记系统附带文章源码部署视频讲解等
基于springboot+vue.js+uniapp的云的学习笔记系统附带文章源码部署视频讲解等
33 0
|
5月前
|
移动开发 JavaScript 前端开发
webgl学习笔记3_javascript的HTML DOM
webgl学习笔记3_javascript的HTML DOM
52 0
webgl学习笔记3_javascript的HTML DOM
|
5月前
|
消息中间件 监控 JavaScript
Node.js中的进程管理:child_process模块与进程管理
【4月更文挑战第30天】Node.js的`child_process`模块用于创建子进程,支持执行系统命令、运行脚本和进程间通信。主要方法包括:`exec`(执行命令,适合简单任务)、`execFile`(安全执行文件)、`spawn`(实时通信,处理大量数据)和`fork`(创建Node.js子进程,支持IPC)。有效的进程管理策略涉及限制并发进程、处理错误和退出事件、使用流通信、谨慎使用IPC以及监控和日志记录,以确保应用的稳定性和性能。
|
5月前
|
JavaScript 前端开发 Java
webgl学习笔记2_javascript基础快速学习
webgl学习笔记2_javascript基础快速学习
44 0
|
5月前
|
前端开发 JavaScript API
JavaScript学习笔记(一)promise与async
JavaScript学习笔记(一)promise与async
|
5月前
|
存储 JavaScript
【ES6系列第二篇】适用JS初学者的Set对象和Map对象学习笔记
【ES6系列第二篇】适用JS初学者的Set对象和Map对象学习笔记
45 0
下一篇
无影云桌面