简体   繁体   中英

Node.js file watching basic example

I'm reading a book named "Node.js the right way".

one of the example codes in the book is that we watch a file "text.txt" for change.

The node.js code is as follows:

const fs = require('fs');
var filename = process.argv[2];
console.log(filename);
var count = 0;
if (!filename) {
   throw Error("A file to watch must be specified!");
} else {
   console.log(filename);
}

fs.watch(filename, function() {
   count = count + 1;
   console.log("File 'text.txt' has been changed ("+count+") times!");
});

console.log("Now watching " + filename + " for changes...");

The book says that the terminal command should be like this:

$ node --harmony watcher.js text.txt

However, this fails, and gives the following error:

fs.js:1237
    throw errnoException(err, 'watch');
    ^
Error: watch ENOENT
    at exports._errnoException (util.js:837:11)
    at FSWatcher.start (fs.js:1237:11)
    at Object.fs.watch (fs.js:1263:11)
    at Object.<anonymous> (/home/ubuntu/workspace/watcher.js:12:4)
    at Module._compile (module.js:434:26)
    at Object.Module._extensions..js (module.js:452:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Function.Module.runMain (module.js:475:10)
    at startup (node.js:117:18)

Unless I typed the full target file path like this:

$ node --harmony watcher.js /home/ubuntu/workspace/text.txt

Which one is correct? and why does it identifies the "watcher.js" file and not the text.txt file although they are both in the same directory? How can I overcome this and just type "text.txt" in the command line?

You should resolve the file in the system. Try this command:

node --harmony watcher.js ./text.txt

You could fix your code with:

const fs = require('fs');
const path = require('path');
var filename = process.argv[2];
if(!path.isAbsolute(filename)){
    filename = path.join(__dirname, filename);
}
console.log(filename);

This has to do with the scoping of the two variable. You should think of

node --harmony watcher.js

as the name of the program you are executing and

text.txt

as the variable you are feeding it. When you run the node executable it has knowledge of the directory you are in so it can 'see' watchers.js. But where does 'test.txt' get used? It's consumed by fs in the actual body of the program which doesn't have any knowledge of the directory you are in. So it's attempting to find /test.txt instead of /home/foo/bar/test.txt

You could use https://nodejs.org/docs/latest/api/globals.html#globals_dirname like this

var filepath = __dirname + filename;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM