node.js child_process module

The child_process module is used to create new child processes. The running result of the child process is stored in the system cache (maximum 200KB). After the child process finishes running, the main process uses the callback function to read the running result of the child process.

Methods of the child_process module:

 

1.exec()   2.execSync()   3.execFile()   4.spawn()   5.fork()   6.send()

 

1.exec() method: The exec method is used to execute the bash command, and its parameter is a command string.

 

var exec = require('child_process').exec;

var ls = exec('ls -l', function (error, stdout, stderr) {
 if (error) {
   console.log(error.stack);
   console.log('Error code: ' + error.code);
 }
 console.log('Child Process STDOUT: ' + stdout);
});

 

 

The exec method of the above code is used to create a new child process, then cache its running results, and call the callback function after the running.

 

The exec method can accept up to two parameters. The first parameter is the shell command to be executed, and the second parameter is the callback function. The function accepts three parameters, which are the error that occurred, the display result of the standard output, and the standard error. Show results.

 

Since standard output and standard error are both stream objects (stream), data events can be monitored, so the above code can also be written as follows.

 

var exec = require('child_process').exec;
var child = exec('ls -l');

child.stdout.on('data', function(data) {
 console.log('stdout: ' + data);
});
child.stderr.on('data', function(data) {
 console.log('stdout: ' + data);
});
child.on('close', function(code) {
 console.log('closing code: ' + code);
});

 

 

The above code also shows that the child process itself has a close event, and a callback function can be set.

 

The code above has one more benefit. After listening to the data event, the result can be output in real time, otherwise the result will be output only after the child process ends. Therefore, if the child process runs for a long time, or runs continuously, the second way of writing is better.

 

Here is another example, assuming there is a child.js file.

 

 

//child.js
var exec = require('child_process').exec;
exec('node -v',function(error, stdout, stderr) {
console.log('stdout: ' + stdout);
console.log('stderr: ' + stderr);
if(error !== null) {
console.log('exec error '+ error);
}
})

 

After running, the output of this file is as follows.

$ node child.js

 

stdout: v0.11.14

 

stderr:

 

The exec method will directly call bash (/bin/sh program) to interpret the command, so if there are parameters entered by the user, the exec method is not safe.

 

var path = ";user input";
child_process.exec('ls -l ' + path, function (err, data){
console.log(data);
})

 

 

The above code means that in the bash environment, ls -l; user input will run directly. If the user enters malicious code, it will pose a security risk. Therefore, in the presence of user input, it is better not to use the exec method, but to use the execFile method.

 

2. execSync() method:

 

execSync is the synchronous execution version of exec.

It can accept two parameters, the first parameter is the command to be executed, and the second parameter is used to configure the execution environment.

 

 

var execSync = require("child_process").execSync;

var SEPARATOR = process.platform === 'win32' ? ';' : ':';
var env = Object.assign({}, process.env);

env.PATH = path.resolve('./node_modules/.bin') + SEPARATOR + env.PATH;

function myExecSync(cmd) {
 var output = execSync(cmd, {
   cwd: process.cwd(),
   env: env
 });

 console.log(output);
}

myExecSync('eslint .');

 

 

 

In the above code, the second parameter of the execSync method is an object. The object's cwd property specifies the script's current directory, and the env property specifies environment variables. The above code stores the ./node_modules/.bin directory into the $PATH variable. In this way, you can refer to the module commands inside the project without adding a path. For example, the eslint command actually executes ./node_modules/.bin/eslint.

 

3.execFile() method:

 

The execFile method directly executes a specific program. The parameters are passed in as an array and will not be interpreted by bash, so it has high security.

 

var child_process = require('child_process');

var path = ".";
child_process.execFile('/bin/ls', ['-l', path], function (err, result) {
   console.log(result)
});

 

 

In the above code, it is assumed that the path comes from user input. If it contains semicolons or backticks, the ls program does not understand their meanings, so the running result cannot be obtained, and the security is improved.

 

4.spawn() method:

 

The spawn method creates a child process to execute a specific command. The usage is similar to the execFile method, but there is no callback function, and the running result can only be obtained by listening for events. It belongs to asynchronous execution and is suitable for long-running child processes.

 

var child_process = require('child_process');

var path = '.';
var ls = child_process.spawn('/bin/ls', ['-l', path]);
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);
});

 

The spawn method accepts two parameters, the first is the executable file and the second is an array of parameters.

 

The spawn object returns an object that represents the child process. The object deploys the EventEmitter interface, and its data event can be monitored to obtain the output of the child process.

 

The spawn method is very similar to the exec method, with a slightly different format.

 

child_process.exec(command, [options], callback)
child_process.spawn(command, [args], [options])

 

 

5.fork() method:

 

The fork method directly creates a child process and executes the Node script. Fork('./child.js') is equivalent to spawn('node', ['./child.js']). Unlike the spawn method, fork establishes a communication channel between the parent process and the child process for communication between processes.

 

 

var n = child_process.fork('./child.js');
n.on('message', function(m) {
 console.log('PARENT got message:', m);
});
n.send({ hello: 'world' });

 

 

 

In the above code, the fork method returns an object representing the inter-process communication pipeline. The object can monitor the message event to obtain the information returned by the child process, and can also send information to the child process.

 

The content of the child.js script is as follows.

 

process.on('message', function(m) {
 console.log('CHILD got message:', m);
});
process.send({ foo: 'bar' });

 

 

In the above code, the child process listens to the message event and sends information to the parent process.

 

6.send() method:

 

After spawning a new process with child_process.fork(), you can send a message to the new process with child.send(message, [sendHandle]). The new process gets the message by listening to the message event.

 

The following example is the code for the main process.

 

var cp = require('child_process');

var n = cp.fork(__dirname + '/sub.js');

n.on('message', function(m) {
 console.log('PARENT got message:', m);
});

n.send({ hello: 'world' });

 

 

Below is the subprocess sub.js code.

 

process.on('message', function(m) {
 console.log('CHILD got message:', m);
});

process.send({ foo: 'bar' });

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326680352&siteId=291194637