2
votes

I am learning Node.js via the book Node.js the Right Way. I am trying to run the following example to watch changes to a file called target.txt that resides in the the same directory as the .js file.

"use strict";
const
    fs = require('fs'),
    spawn = require('child_process').spawn,
    filename = process.argv[2];
if (!filename) {
    throw Error("A file to watch must be specified!");
}
fs.watch(filename, function () {
    let ls = spawn('ls', ['-lh', filename]);
    ls.stdout.pipe(process.stdout);
});
console.log("Now watching " + filename + " for changes...");

I get the following error when I change the text file and save it:

events.js:160 throw er; // Unhandled 'error' event ^

Error: spawn ls ENOENT at exports._errnoException (util.js:1018:11) at Process.ChildProcess._handle.onexit (internal/child_process.js:193:32) at onErrorNT (internal/child_process.js:367:16) at _combinedTickCallback (internal/process/next_tick.js:80:11) at process._tickCallback (internal/process/next_tick.js:104:9)

Node.js version: v6.11.0

IDE: Visual Studio Code 1.13.1

OS: Windows 10 64x

1

1 Answers

3
votes

There's no ls on Windows, you should use dir instead.

However, that's not an executable. To run .bat and .cmd files you can:

  • Spawn cmd.exe and pass those files as arguments:

    require('child_process').spawn('cmd', ['/c', 'dir']);
    
  • Use spawn with the shell option set to true:

    require('child_process').spawn('dir', [], { shell: true });
    
  • Use exec instead of spawn:

    require('child_process').exec('dir', (err, stdout, stderr) => { ... });
    

For more on that, take a look at this section in the official docs.

EDIT:

I'm not sure I understood you question in the comment correctly, but if you go for the second option, for example, you code will look like this:

...

fs.watch(filename, function () {
    let dir = spawn('dir', [filename], { shell: true });

    dir.stdout.pipe(process.stdout);
});

...

Please, keep in mind you may need to adjust this code slightly. I'm writing all this from memory as I don't have access to a Windows machine right now, so I can't test it myself.