1

I am currently developing a program where you can create virtual machines in VirtualBox as a project. To do this I need to run 2 commands synchronously as one creates a VM and the other modifies that VM. Here is the code.

nodecmd.run(cmd);
var cmd1 = createCmd1.concat(createServ);
console.log(cmd1);
var cmd2 = cmd1.concat(' --natpf1 "ssh,tcp,,302');
console.log(cmd2);
var cmd3 = cmd2.concat(createServ);
console.log(cmd3);
var cmd4 = cmd3.concat(',,22"');
console.log(cmd4);
nodecmd.run(cmd4);

Thanks!

3
  • This depends a lot on whatever nodecmd is and how it would return child processes. Commented Feb 22, 2019 at 14:04
  • I am a complete beginner please may you explain what a child process is please? Commented Feb 22, 2019 at 14:07
  • I have completed what I need to do now with child processes. Thanks! Commented Feb 22, 2019 at 14:17

2 Answers 2

3

I have found that I can just use child processes:

const execSync = require('child_process').execSync;
code = execSync('node -v');
Sign up to request clarification or add additional context in comments.

Comments

1

I think you should use promise to chain your executions steps. Promises are good for handling asynchronous chaining events.

node-cmd support promise using bluebird.

const promise = require('bluebird');
const nodecmd = require('node-cmd');

const getAsync = promise.promisify(nodecmd.get, {
    multiArgs: true,
    context: nodecmd
});

let cmd0 = 'node -v';
let cmd1 = 'pwd';
let cmd2 = 'mkdir -p xxx';

getAsync(cmd0)
    .then(result => console.log(result))
    .then(() => getAsync(cmd1))
    .then(result => console.log(result))
    .then(() => getAsync(cmd2))
    .then(result => console.log(result))
    .catch(err => {
        console.log('cmd err', err)
    })

Try this in action - https://jsitor.com/2ZZPZqtvb

3 Comments

I just realised that node-cmd was probably created to use commands asynchronously. I have upvoted but it doesn't show because I don't have 15 rep.
Yes, I agree but you can use it along with the promises to execute it in sync.
Thanks, this helped me come out of a messy work around (sleeping for minutes before moving to next step).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.