Search code examples
javascriptnode.jsexecchild-processspawn

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.


Solution

  • 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");
    });