Node.js文件观看的基本示例

Node.js file watching basic example

本文关键字:js 文件观 Node      更新时间:2023-09-26

我正在读一本名为《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"?

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

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

这与两个变量的作用域有关。你应该想想

node --harmony watcher.js

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

text.txt

作为你提供给它的变量。当你运行节点可执行文件时,它知道你所在的目录,这样它就可以"看到"watchers.js。但是"test.txt"在哪里使用呢?它被fs在程序的实际主体中使用,该主体对您所在的目录一无所知。因此,它试图查找/test.txt而不是/home/foo/bar/test.txt

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

var filepath = __dirname + filename;