0

On button click I can open a command prompt using Node.js child process.

var child_process = require('child_process');

 let command = `start cmd.exe /K "cd /D c:/Users && java"`

 let process = child_process.spawn(command, [], { shell: true }) //use `shell` option

using above code I can open a command prompt and run Java command at specified location.

Now my question how can I do same process in background without opening command prompt (cmd) ?

2
  • Use exec instead of spawn Commented Jul 12, 2019 at 6:08
  • Hi @Vishal-Lia can you tell me more specific like how can I run in background using exec ? Commented Jul 12, 2019 at 6:12

1 Answer 1

2

Spawn has the cwd (Current Working Directory) option which you can point to open up the process.

var child_process = require('child_process');

let bin = 'java';
let cliArgs= ['-version'];
let options = {
  spawn: true,
  cwd: 'c:/Users'
}

let command = child_process.spawn(bin, cliArgs, options ) //use `shell` option

command.stdout.on('data', (data) => {
  console.log(`stdout: ${data}`);
});

command.stderr.on('data', (data) => {
  console.log(`stderr: ${data}`);
});

command.on('close', (code) => {
  console.log(`child process exited with code ${code}`);
});
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for the answer. If I use above code I'm getting following error ` let arguments = ['-version']; ^^^^^^^^^ SyntaxError: Unexpected eval or arguments in strict mode`
Thank you it worked with little modification. I removed let arguments = ['-version']; and added let bin = 'java -version'; Also passed [] in let command = child_process.spawn(bin, [], options )
I updated my code, "arguments" is a javascript object inside functions. Since you were using strict mode the error was triggered because it's not defined anywhere. I just had to rename it. Try with the renamed variable again, it's not good practice to use the arguments along with the executable as you mentioned this let bin = 'java -version';. Your CLI arguments should be in the 2nd parameter, the array, which will be .join-ed with a space before executing the full command.

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.