Node.js文件正在观看基本示例

时间:2015-11-13 13:44:43

标签: javascript node.js

我正在读一本名为" Node.js正确方法的书"。

本书中的一个示例代码是我们观看文件" 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

哪一个是正确的?为什么它会识别&#34; watcher.js&#34;文件,而不是text.txt文件,虽然它们都在同一个目录中?我怎样才能克服这个问题,只需输入&#34; text.txt&#34;在命令行?

2 个答案:

答案 0 :(得分:1)

您应该解析系统中的文件。试试这个命令:

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);

答案 1 :(得分:1)

这与两个变量的范围有关。你应该想到

node --harmony watcher.js

作为您正在执行的程序的名称和

text.txt

作为你喂它的变量。当您运行节点可执行文件时,它知道您所在的目录,因此它可以查看&#39; watchers.js。但是&#39; test.txt&#39;习惯了?它是由程序的实际主体中的 fs 消耗的,它不知道您所在的目录。因此它正在尝试查找/测试。 txt而不是/home/foo/bar/test.txt

你可以像这样使用https://nodejs.org/docs/latest/api/globals.html#globals_dirname

var filepath = __dirname + filename;