child_process

2022-02-17  本文已影响0人  kzc爱吃梨

child_process

使用目的

API

exec(cmd,options,fn)

const { exec } = require('child_process');

exec('ls ../', (error, stdout, stderr)=> {
    console.log(error);
    console.log(stdout);
    console.log(stderr);
})
image.png

const { exec } = require('child_process');
const stream = exec('ls ../')

stream.stdout.on('data', (chunk)=> {
    console.log('stdout' + chunk)
})
stream.stderr.on('data', (chunk)=> {
    console.log('stderr' + chunk)
})
stream.on('close', (code)=> {
    console.log('closing code:' + code)
})

Promise

const { exec } = require('child_process');
const util = require("util");

const exec2 = util.promisify(exec)

exec2('ls ../').then(data=> {
    console.log(data.stdout)
})

options

几个常用的选项

const { execFile } = require('child_process');

const userInput = ".";
execFile('ls', ['-la', userInput], {
    cwd: 'c:\\',   // 改变命令的目录,默认是当前目录
    env: {NODE_ENV: 'development'},  // 环境变量
    maxBuffer: 1024 * 1024,
    shell: '路径'
}, (error, stdout)=> {
    console.log(error)
    console.log(stdout)
})

API

execFile
执行特定的程序
命令行的参数要用数组形式传入,无法注入同步版本:execFileSync

const { execFile } = require('child_process');

const userInput = ".";
execFile('ls', ['-la', userInput], (error, stdout)=> {
    console.log(error)
    console.log(stdout)
})

支持流吗?

const { execFile } = require('child_process');

const userInput = ".";

const stream = execFile('ls', ['-la', userInput])

stream.stdout.on('data', (chunk)=> {
    console.log(chunk)
})

API

spawn

经验
能用 spawn的时候就不要用execFile

const { spawn } = require('child_process');

const userInput = ".";
const stream = spawn('ls', ['-la', userInput], {
    cwd: 'c:\\',   // 改变命令的目录,默认是当前目录
    env: {NODE_ENV: 'development'},  // 环境变量
})

stream.stdout.on('data', (chunk) => {
    console.log(chunk.toString())
})

API

fork

特点

n.js

const {fork} = require('child_process')

const n = fork('./child.js');
n.on('message', (msg)=> {
    console.log('父进程得到子进程传的值', msg)
})
n.send({
    hello: 'world'
})

child.js

setTimeout(()=> {
    process.send({foo: 'bar'})
}, 2000)

process.on('message', (msg)=> {
    console.log('子进程得到父进程的值');
    console.log(msg);
})
image.png
上一篇 下一篇

猜你喜欢

热点阅读