如果有多个grep,怎么写到上面的语句中?例如cat /dev/urandom |od -x|tr -d ' '|head -n 1
在网上找了下,发现用以下的方法也行,使用spawn
和exec
有什么区别呢?
const exec = require('child_process').exec;
exec('cat /dev/urandom |od -x|tr -d ' '|head -n 1', (error, stdout, stderr) => {
if (error) {
console.error(`exec error: ${error}`);
return;
}
console.log(`stdout: ${stdout}`);
console.log(`stderr: ${stderr}`);
});
天蓬老师2017-04-17 15:38:29
If not encapsulated, you need to listen to multiple events, for example cat /dev/urandom |od -x|tr -d ' '|head -n 1
const spawn = require('child_process').spawn;
const cat = spawn('cat', ['/dev/urandom']);
const od = spawn('od',['-x']);
const tr = spawn('tr',['-d'," "]);
const head = spawn('head', ['-n',1]);
cat.stdout.on('data', data => od.stdin.write(data));
cat.on('close', (code) => od.stdin.end());
od.stdout.on('data', data => tr.stdin.write(data));
od.on('close', (code) => tr.stdin.end());
tr.stdout.on('data', data => head.stdin.write(data));
tr.on('close', (code) => head.stdin.end());
head.stdout.on('data', data => console.log(`${data}`));
head.stdin.on('error',err=>head.stdin.end());
You can also specify a pipe when spwan creates a child process, such as this
const spawn = require('child_process').spawn;
const cat = spawn('cat', ['/dev/urandom'], {stdio: 'pipe'});
const od = spawn('od',['-x'], {stdio: [cat.stdout, 'pipe', 'pipe']});
const tr = spawn('tr',['-d',' '], {stdio: [od.stdout, 'pipe', 'pipe']});
const head = spawn('head', ['-n',1], {stdio: [tr.stdout, 'pipe', 'pipe']});
head.stdout.on('data', data => console.log(`${data}`));
head.stdin.on('error',err=>head.stdin.end());
In actual environment, the information on stderr must be processed
天蓬老师2017-04-17 15:38:29
The example you gave doesn’t have grep?
https://nodejs.org/api/child_...
Multiple options are passed as the second parameter in the form of an array: ls -lh /usr
const spawn = require('child_process').spawn;
const ls = spawn('ls', ['-lh', '/usr']);
The example you gavecat /dev/urandom |od -x|tr -d ' '|head -n 1
Just follow the pipeline you screenshot and do it separately:
// cat /dev/urandom
const cat = spawn('cat',['/dev/urandom']);
//od -x
const od = spawn('od',['-x']);
//tr -d ' '
const tr = spawn('tr', ['-d',"' '"]);
//head -n 1
const head = spwan('head', ['-n','1']);
As for the pipeline, see how it is written in the example you screenshot, it is how the next command is executed in the callback