我正在讀一本名爲「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
哪一個是正確的?爲什麼它會識別「watcher.js」文件而不是text.txt文件,儘管它們都在同一目錄中?我如何克服這一點,只需在命令行中鍵入「text.txt」?
我的猜測是的text.txt - 是watcher.js輸入,watcher.js在運行時,正在運行的程序的位置是不一樣的「本地路徑'(如果它不同,也許從節點安裝目錄中)。什麼是node.js安裝目錄? –
'ENOENT'意思是「沒有進入」。這是與文件路徑 –
有關的一些錯誤沒有要觀看的文件。我認爲那也是你的問題。 ... – 82Tuskers