Execute bash command in Node.js and get exit code

后端 未结 4 966
忘了有多久
忘了有多久 2020-12-13 02:02

I can run a bash command in node.js like so:

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

function puts(error, stdout, stderr) { s         


        
4条回答
  •  醉梦人生
    2020-12-13 02:35

    child_process.spawnSync()

    This function exposes the nicest sync interface: https://nodejs.org/api/child_process.html#child_process_child_process_spawnsync_command_args_options

    Example:

    #!/usr/bin/env node
    
    const child_process = require('child_process');
    let out;
    
    out = child_process.spawnSync('true');
    console.log('status: ' + out.status);
    console.log('stdout: ' + out.stdout.toString('utf8'));
    console.log('stderr: ' + out.stderr.toString('utf8'));
    console.log();
    
    out = child_process.spawnSync('false');
    console.log('status: ' + out.status);
    console.log('stdout: ' + out.stdout.toString('utf8'));
    console.log('stderr: ' + out.stderr.toString('utf8'));
    console.log();
    
    out = child_process.spawnSync('echo', ['abc']);
    console.log('status: ' + out.status);
    console.log('stdout: ' + out.stdout.toString('utf8'));
    console.log('stderr: ' + out.stderr.toString('utf8'));
    console.log();
    

    Output:

    status: 0
    stdout: 
    stderr: 
    
    status: 1
    stdout: 
    stderr: 
    
    status: 0
    stdout: abc
    
    stderr: 
    
    

    Tested in Node.js v10.15.1, Ubuntu 19.10.

提交回复
热议问题