This is the fourth day of my participation in Gwen Challenge
preface
A long time ago, when I first came into contact with shell commands, I used to think that if a shell script could be triggered by an interface, it would greatly liberate our useless operations (deployment process). Later, I found that Github provides an API in the form of Webhook. Nodejs child_process allows you to listen for change notifications in a repository. Instead of talking about Webhooks today, we’ll focus on nodeJS child_process, which is used to create child processes that can be performed by calling shell commands directly from the nodeJS program. Here’s what he might do:
exec
Exec (command, callback) exec takes two arguments. The first argument is a string representing the command line operation you want to perform, and the second is an error-first callback containing the err object and the output of the command line, as follows:
const {exec } = require('child_process');
exec('ls'.(err, stdout, stderr) = > {
console.log('err', err); // err null
console.log('stdout', stdout); // stdout xxxx
console.log('stderr', stderr); // stderr
})
Copy the code
execFile
Function signature: ExecFile (file, options, callback), execFile and exec are different in that the first parameter is an executable file, which can be a system environment variable, the second parameter is a passed parameter, and the third parameter is an error priority callback. Specific use is as follows
const {execFile} = require('child_process');
execFile('node'['./20210611/exec.js'].(err, stdout, stderr) = > {
console.log('err', err); // err null
console.log('stdout', stdout); // stdout err null stdout xxx stderr
console.log('stderr', stderr); // stderr
})
Copy the code
Err is null. Stdout is exec. Stderr is null. Instead of printing it once on the console after execution, we used the rest of the method
spawn
Function signature: Spawn (command, args, options), spawn receives three arguments. The first argument is the command to execute, the second argument is the array, and the third argument is the configuration item. Importantly, spawn has its own stream information. We can establish the relationship between the master process and the child process to output information in real time, as follows
const {spawn} = require('child_process');
const child = spawn('ps'['-ef'])
child.stdout.pipe(process.stdout); // Output a lot
child.stderr.pipe(process.stderr);
Copy the code
conclusion
That’s all for today. Child_process, of course, is more than that, its playability is far from being explored. In the next few days, I will focus on the output of the main modules of the command line tool. GitHub code address