lonelymo
lonelymo

Reputation: 4202

Calling Shellscript in NodeJs

I have a Node Js program that has three parts to it.

The first part executes and returns the IP and User The second part is calling the following shellscript

   #!/bin/bash
    IP=$1
    User=$2
    ssh -i /Users/cer.pem ubuntu@$IP "cd /home/$ && ls -lth" >> /Users/outcome.txt

Upon successful creation of the outcome.txt, I have to continue doing other stuff in the third part.

I did find two items relevant to thi Run shell script with node.js (childProcess) & Node.js Shell Script And Arguments, but these arent exactly solving my problem as it doesnt talk handling the sync nature of shellsrcipt.

More info about how to really work with child_process would really help. 1) How do I pass the IP and User to the 2nd node module embedding the shellscript? 2) How do I extract the dir listing from the outcome of shellscript?

Can anyone please help me here?

Upvotes: 0

Views: 985

Answers (1)

Peter Lyons
Peter Lyons

Reputation: 146164

So if your goal is to list the contents of a folder on a remote system via ssh, be aware that this can be done several ways. Use child_process and a shell script is OK, but you could also use node-control or mscdex/ssh2 (and probably numerous others).

But in any case, when the remote work is being done, your node code will continue to execute asynchronously. Even if your script is synchronous, you have to write your control flow logic in your node.js code asynchronously.

Start with some basic nested callbacks.

function getIpAndUser(callback) {
  //get them then do
  callback(null, ip, user);
}

function listDirectory(ip, user, callback) {
  //do your child_process.exec here
  //eventually call
  callback(null, output)
}

function thirdPart() {

}

//combine them together correctly:

getIpAndUser(function (error, ip, user) {
  if (error) {
    console.error(error);
    return;
  }
  listDirectory(ip, user, function () {
    if (error) {
      console.error(error);
      return;
    }
    thirdPart();
  });
});
}

Once you grok that you can rewrite the control flow using something like async.js or a promises library if you so choose.

To address your further questions in the comments:

1) child_process.exec('list_dir.sh ' + ip + ' ' + user, callback)

Note you should eventually escape those arguments properly and probably switch to child_process.execFile, but start with that.

2) The way they do in the example that is right there in the documentation

Upvotes: 2

Related Questions