The original published in my blog Node. Js execution system command | ether

When using Node.js, we always need to execute some system commands, interact with the system, or call other languages. What should we do? This module, of course, uses the child_process module, which translates as child process. As the name suggests, this module works mainly by producing child processes.

A,execwithexecSync

This is the simplest function in the child_process module and is used to execute a fixed system command

const { exec } = require('child_process');
// Outputs the files and folders in the current directory (not necessarily the directory where the code resides)
exec('ls -l', (err, stdout, stderr) => {
    if(err) {
        console.log(err);
        return;
    }
    console.log(`stdout: ${stdout}`);
    console.log(`stderr: ${stderr}`);
})
Copy the code

The exec function takes the command to execute as its first argument, the configuration option as its second argument, the callback function as its third argument, and the child’s working directory as one of the more common arguments

const { exec } = require('child_process');
const path = require('path') :// Run hexo g in the scripts folder in the current directory
exec('hexo g', { cwd: path.join(process.cwd(), 'scripts') }, (err, stdout, stderr) => {
    if(err) {
        console.log(err);
        return;
    }
    console.log(`stdout: ${stdout}`);
});
Copy the code

ExecSync is a synchronized version of exec, but either execSync or exec results in strings or Buffer objects that typically require further processing.

For details, see exec configuration and execSync configuration

Second,execFilewithexecFileSync

These two functions execute an executable file, as shown in the following example:

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

execFile('example.py', [], (err, stdout, stderr) => {
    if(err) {
        console.log(err);
        return;
    }
    console.log(`stdout: ${stdout}`);
});

const stdout = execFileSync('node'['-v']);
console.log(stdout);
Copy the code

Similar to exec, the first argument is the file path to execute, the second is the parameter array, the third is the configuration, and the fourth is the callback function. Of course, all but the first can be omitted

Note: The file to be executed must have executable permissions. If it is a language-specific script like.py, specify the interpreter program path at the beginning

See execFile Configuration, execFileSync Configuration

Three,spawnwithspawnSync

All functions in the child_process module are implemented based on the spawn and spawnSync functions. In other words, the spawn and spawnSync functions are the most fully configured, and all other functions are encapsulated and modified. Spawn (command[, args][, options]) child_process.spawn(command[, args][, options])

It creates a new process using the specified command-line arguments, and spawn returns an object with stdout and stderr streams. You can use the stdout stream to read the data returned by the child process to Node.js. Stdout has ‘data’,’end’, and events that a normal stream has. When you want the child process to return a lot of data to Node, such as image processing, reading binary data, etc., you should use the spawn method

const {spawn}  = require('child_process');
const fs = require('fs');
const spawnObj = spawn('ping'['127.0.0.1'] and {encoding: 'utf-8'});
spawnObj.stdout.on('data'.function(chunk) {
    console.log(chunk.toString());
});
spawnObj.stderr.on('data', (data) => {
  console.log(data);
});
spawnObj.on('close'.function(code) {
    console.log('close code : ' + code);
})
spawnObj.on('exit', (code) => {
    console.log('exit code : ' + code);
    fs.close(fd, function(err) {
        if(err) {
            console.error(err); }}); });Copy the code