Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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

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

Problem

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.

Problem courtesy of: tetri

Solution

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.

Solution courtesy of: gustavohenke

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

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

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×