Search code examples
node.jsspawn

child_process nodejs doesn't fire error if file doesn't exists


I should exec a VBS script by Nodejs and so I'm using child_process.

My problem is that if there is an error on spawn process it never fires error event.

const { spawn } = require( 'child_process' );

const vbs = spawn( 'cscript.exe', [ vbsPath] );
vbs.on('error', function( err ){
   console.log(err);
})
vbs.on('close', async function(code) {
   console.log(code)
});

vbsPath is the path of vbs and if I try to put wrong path or add an error in vbs it fires always close event with code 1 instead of 0. but my question is:

Why it never fires the error event? Is the code of close event reliable for know if the script return error?


Solution

  • The process is spawned well, it is due to this that you don't receive the error.

    From docs

    The 'error' event is emitted whenever:

    The process could not be spawned, or

    The process could not be killed, or

    Sending a message to the child process failed.

    For example, if you write const vbs = spawn('ciao', ['vbsPath']) you will receive the error event.