Exec : display stdout “live”

前端 未结 9 1165
你的背包
你的背包 2020-11-29 15:08

I have this simple script :

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

exec(\'coffee -cw my_file.coffee\', function(error, stdout, stderr) {
    console.lo         


        
相关标签:
9条回答
  • 2020-11-29 15:44

    child_process.spawn returns an object with stdout and stderr streams. You can tap on the stdout stream to read data that the child process sends back to Node. stdout being a stream has the "data", "end", and other events that streams have. spawn is best used to when you want the child process to return a large amount of data to Node - image processing, reading binary data etc.

    so you can solve your problem using child_process.spawn as used below.

    var spawn = require('child_process').spawn,
    ls = spawn('coffee -cw my_file.coffee');
    
    ls.stdout.on('data', function (data) {
      console.log('stdout: ' + data.toString());
    });
    
    ls.stderr.on('data', function (data) {
      console.log('stderr: ' + data.toString());
    });
    
    ls.on('exit', function (code) {
      console.log('code ' + code.toString());
    });
    
    0 讨论(0)
  • 2020-11-29 15:47

    After reviewing all the other answers, I ended up with this:

    function oldSchoolMakeBuild(cb) {
        var makeProcess = exec('make -C ./oldSchoolMakeBuild',
             function (error, stdout, stderr) {
                 stderr && console.error(stderr);
                 cb(error);
            });
        makeProcess.stdout.on('data', function(data) {
            process.stdout.write('oldSchoolMakeBuild: '+ data);
        });
    }
    

    Sometimes data will be multiple lines, so the oldSchoolMakeBuild header will appear once for multiple lines. But this didn't bother me enough to change it.

    0 讨论(0)
  • 2020-11-29 15:51

    I have found it helpful to add a custom exec script to my utilities that do this.

    utilities.js

    const { exec } = require('child_process')
    
    module.exports.exec = (command) => {
      const process = exec(command)
    
      process.stdout.on('data', (data) => {
        console.log('stdout: ' + data.toString())
      })
    
      process.stderr.on('data', (data) => {
        console.log('stderr: ' + data.toString())
      })
    
      process.on('exit', (code) => {
        console.log('child process exited with code ' + code.toString())
      })
    }
    

    app.js

    const { exec } = require('./utilities.js')
    
    exec('coffee -cw my_file.coffee')
    
    0 讨论(0)
提交回复
热议问题