Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
598 views
in Technique[技术] by (71.8m points)

bash - Node.js Shell Script And Arguments

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 it. However, the script itself needs arguments like the username, the password and the real name of the user. I still can't figure out how to pass those arguments to the script doing something like this:

var commands = data.toString().split('
').join(' && ');

Does anyone have an idea how I can pass those arguments and execute the bash script within node.js over an ssh connection. thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...