Node.js Shell Script And Arguments

后端 未结 3 1790
再見小時候
再見小時候 2020-11-28 21:18

I need to execute a bash script in node.js. Basically, the script will create user account on the system. I came across this example which gives me an idea how to go about i

相关标签:
3条回答
  • 2020-11-28 22:09
    var exec = require('child_process').exec;
    
    var child = exec('cat *.js | wc -l', function(error, stdout, stderr) {
      if (error) console.log(error);
      process.stdout.write(stdout);
      process.stderr.write(stderr);
    });
    

    This way is nicer because console.log will print blank lines.

    0 讨论(0)
  • 2020-11-28 22:22

    You can use process.argv. It's an array containing the command line arguments. The first element will be node the second element will be the name of the JavaScript file. All next elements will be any additional command line you given.

    You can use it like:

    var username = process.argv[2];
    var password = process.argv[3];
    var realname = process.argv[4];
    

    Or iterate over the array. Look at the example: http://nodejs.org/docs/latest/api/all.html#process.argv

    0 讨论(0)
  • 2020-11-28 22:24

    See the documentation here. It is very specific on how to pass command line arguments. Note that you can use exec or spawn. spawn has a specific argument for command line arguments, while with exec you would just pass the arguments as part of the command string to execute.

    Directly from the documentation, with explanation comments inline

    var util  = require('util'),
        spawn = require('child_process').spawn,
        ls    = spawn('ls', ['-lh', '/usr']); // the second arg is the command 
                                              // options
    
    ls.stdout.on('data', function (data) {    // register one or more handlers
      console.log('stdout: ' + data);
    });
    
    ls.stderr.on('data', function (data) {
      console.log('stderr: ' + data);
    });
    
    ls.on('exit', function (code) {
      console.log('child process exited with code ' + code);
    });
    

    Whereas with exec

    var util = require('util'),
        exec = require('child_process').exec,
        child;
    
    child = exec('cat *.js bad_file | wc -l', // command line argument directly in string
      function (error, stdout, stderr) {      // one easy function to capture data/errors
        console.log('stdout: ' + stdout);
        console.log('stderr: ' + stderr);
        if (error !== null) {
          console.log('exec error: ' + error);
        }
    });
    

    Finally, note that exec buffers the output. If you want to stream output back to a client, you should use spawn.

    0 讨论(0)
提交回复
热议问题