简体   繁体   中英

Node.js calling bash script via spawn(): ENOENT

This will throw a ENOENT error:

const cmd = 'bash my/path/to/script.sh';
const process = spawn(cmd);
process.on('exit', (code) => {
    console.log("Child exited");
});

While this will not and execute the script as expected:

const cmd = 'bash my/path/to/script.sh';
exec(cmd, function(err, stdout, stderr) {
    console.log(stdout);
});

Now, I would like to have the datastream from spawn() and get it working. Any suggestions where this behavior could come from?

I checked pwd and the current working directory is the same for both.

Looks like the problem is that exec takes a single command argument as a string with arguments separated by spaces, but for spawn you need to provide the command (bash) and then the arguments as an array:

https://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback

https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options

try this:

const process = spawn('bash', ['my/path/to/script.sh']);
process.on('exit', (code) => {
    console.log("Child exited");
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM