tetri
tetri

Reputation: 3584

NodeJS: throw er; //Unhandled 'error' event (events.js:72) when using child_process spawn method

I've made an node.js app to list all .txt files from a directory recursively and, for each one, do some stuff.

Here's my app.js:

var spawn = require('child_process').spawn,
    dir = spawn('dir', ['*.txt', '/b']);

dir.stdout.on('data', function (data) {
    //do some stuff with each stdout line...
    console.log('stdout: ' + data);
});

dir.stderr.on('data', function (data) {
    //throw errors
    console.log('stderr: ' + data);
});

dir.on('close', function (code) {
    console.log('child process exited with code ' + code);
});

When I run node app.js via console, I get the error message below:

events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: spawn ENOENT
    at errnoException (child_process.js:980:11)
    at Process.ChildProcess._handle.onexit (child_process.js:771:34)

I'm using node v0.10.13 at win32 environment.

I do this way (spawn) because I want to handle stdout line by line (the exec method release entire stdout as one string).

* UPDATE *

By the way, using spawn for child_process does not guarantee that the output for cmd dir will be line by line. I've created a question for that too.

Upvotes: 21

Views: 44239

Answers (2)

gustavohenke
gustavohenke

Reputation: 41440

That happen because dir is not a executable in Windows. It's a command from the shell.
The solution for your problem is the following:

var dir = spawn('cmd', ['/c', 'dir']);
dir.stdout.on("data", function() {
    // do things
})

This exact problem was here also.

Upvotes: 21

Laurent Perrin
Laurent Perrin

Reputation: 14881

Several things:

  • dir is not a real executable in windows, so node.js cannot find the program you want to run.
  • You didn't bind an 'error' handler to your child process and the event was turned into an exception that crashed your node instance. Do this:
dir.on('error', function (err) {
  console.log('dir error', err);
});
  • Use fs.readdir instead. It's a standard node.js API that does the same thing.

Upvotes: 15

Related Questions