我正在读一本名为“Node.js the right way”的书。
书中的示例代码之一是我们观察文件“text.txt”的变化。
node.js代码如下:
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...");
书上说终端命令应该是这样的:
$ node --harmony watcher.js text.txt
但是,这失败了,并给出了以下错误:
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)
除非我像这样输入完整的目标文件路径:
$ node --harmony watcher.js /home/ubuntu/workspace/text.txt
哪个是正确的?为什么它识别“watcher.js”文件而不是 text.txt 文件,尽管它们都在同一目录中?我怎样才能克服这个问题并在命令行中输入“text.txt”?
最佳答案
您应该在系统中解析该文件。试试这个命令:
node --harmony watcher.js ./text.txt
您可以修复您的代码:
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);
关于javascript - Node.js 文件观看基本示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33694154/