Execute a command line binary with Node.js

后端 未结 12 2219
星月不相逢
星月不相逢 2020-11-22 01:39

I am in the process of porting a CLI library from Ruby over to Node.js. In my code I execute several third party binaries when necessary. I am not sure how best to accomplis

12条回答
  •  你的背包
    2020-11-22 02:15

    If you don't mind a dependency and want to use promises, child-process-promise works:

    installation

    npm install child-process-promise --save
    

    exec Usage

    var exec = require('child-process-promise').exec;
    
    exec('echo hello')
        .then(function (result) {
            var stdout = result.stdout;
            var stderr = result.stderr;
            console.log('stdout: ', stdout);
            console.log('stderr: ', stderr);
        })
        .catch(function (err) {
            console.error('ERROR: ', err);
        });
    

    spawn usage

    var spawn = require('child-process-promise').spawn;
    
    var promise = spawn('echo', ['hello']);
    
    var childProcess = promise.childProcess;
    
    console.log('[spawn] childProcess.pid: ', childProcess.pid);
    childProcess.stdout.on('data', function (data) {
        console.log('[spawn] stdout: ', data.toString());
    });
    childProcess.stderr.on('data', function (data) {
        console.log('[spawn] stderr: ', data.toString());
    });
    
    promise.then(function () {
            console.log('[spawn] done!');
        })
        .catch(function (err) {
            console.error('[spawn] ERROR: ', err);
        });
    

提交回复
热议问题