2 回答

TA貢獻(xiàn)1868條經(jīng)驗(yàn) 獲得超4個(gè)贊
child_process.exec
:
const { exec } = require('child_process');exec('cat *.js bad_file | wc -l', (err, stdout, stderr) => { if (err) { // node couldn't execute the command return; } // the *entire* stdout and stderr (buffered) console.log(`stdout: ${stdout}`); console.log(`stderr: ${stderr}`);});
const util = require('util');const exec = util.promisify(require('child_process').exec);async function ls() { const { stdout, stderr } = await exec('ls'); console.log('stdout:', stdout); console.log('stderr:', stderr);}ls();
child_process.spawn
:
const { spawn } = require('child_process');const child = spawn('ls', ['-lh', '/usr']);// use child.stdout.setEncoding('utf8'); if you want text chunkschild.stdout.on('data', (chunk) => { // data from standard output is here as buffers});// since these are streams, you can pipe them elsewherechild.stderr.pipe(dest); child.on('close', (code) => { console.log(`child process exited with code ${code}`);});
child_process.execSync
:
const { execSync } = require('child_process');// stderr is sent to stderr of parent proces s// you can set options.stdio if you want it to go elsewherelet stdout = execSync('ls');
const { spawnSync} = require('child_process');const child = spawnSync('ls', ['-lh', '/usr']);console.log('error', child.error); console.log('stdout ', child.stdout);console.log('stderr ', child.stderr);
注:
child_process.exec
:
var exec = require('child_process').exec;var cmd = 'prince -v builds/pdf/book.html -o builds/pdf/book.pdf'; exec(cmd, function(error, stdout, stderr) { // command output is in stdout});
child_process.spawn
:
var spawn = require('child_process').spawn;var child = spawn('prince', [ '-v', 'builds/pdf/book.html', '-o', 'builds/pdf/book.pdf']);child.stdout.on('data', function(chunk) { // output will be here in chunks});// or if you want to send output elsewherechild.stdout.pipe(dest);
child_process.execFile
spawn
exec
var execFile = require('child_process').execFile;execFile(file, args, options, function(error, stdout, stderr) { // command output is in stdout});
spawn
exec
ChildProcess
.
添加回答
舉報(bào)