看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..."); 

这本书说terminal命令应该是这样的:

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

除非我input完整的目标文件path,如下所示:

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

哪一个是正确的? 为什么它识别“watcher.js”文件,而不是text.txt文件,尽pipe它们都在同一目录中? 我怎样才能克服这一点,只需在命令行中键入“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); 

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

 node --harmony watcher.js 

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

 text.txt 

作为你喂养它的variables。 当你运行节点可执行文件时,它已经知道你所在的目录,所以它可以'看到'watchers.js。 但是'test.txt'在哪里使用? 它在程序的实际主体中被fs占用,它不知道你所在的目录。所以它试图find/test.txt而不是/home/foo/bar/test.txt

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

 var filepath = __dirname + filename;