【问题标题】:Node FS module throws ENOENT Error When Trying To Use Watch MethodNode FS 模块在尝试使用 Watch 方法时抛出 ENOENT 错误
【发布时间】:2018-09-09 07:56:28
【问题描述】:

我使用的是 macOS 10.13.4 和 Node 版本 8.11.4。 我正在尝试遵循来自 tutsplus.com 的名为 Node From Scratch 的简单教程。第二个视频首先需要 FS 模块,然后在文件上调用 watch 方法来监视文件的更改。

'use strict';

const fs = require( 'fs' );

fs.watch( 'stylesheet.css', () => console.log( 'File Has Been Updated' ) );

console.log( "Application Has Started And Is Listening For Changes" );

每当我尝试使用 Node 在终端中运行 js 文件时,我都会收到错误消息

fs.js:1384
throw error;
^
Error: watch stylesheet.css ENOENT
at _errnoException (util.js:992:11)
at FSWatcher.start (fs.js:1382:19)
at Object.fs.watch (fs.js:1408:11)
at Object.<anonymous> (/Downloads/filewatcher.js:5:4)
at Module._compile (module.js:652:30)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
at Function.Module.runMain (module.js:693:10)

我似乎无法在网上找到任何关于为什么会发生这种情况的信息。谁能帮忙。

【问题讨论】:

  • 你有一个名为 stylesheet.css 的文件吗?
  • @ashishsingh 是的,我愿意
  • 我不确定,请检查一次拼写,它应该与这个js文件在同一目录下
  • @ashishsingh 谢谢,是的,我已经检查了拼写,它在同一个目录中,但我仍然没有运气。
  • 哦,如果您不是初学者并且可以读取文件,您可以做一个实验来读取类似位置的文件;将它命名为 b.css 并尝试阅读它.. 这样你就知道你的设置是正确的

标签: javascript node.js node-modules fs


【解决方案1】:

正如 cmets 所指出的,您在绝对路径与相对路径以及节点如何处理当前工作目录方面遇到了问题。

运行以下命令可以最好地证明问题的症结:

const path = require('path');
console.log(path.resolve('foo'));
console.log(path.resolve('./foo'));

在后一种情况下,node 会根据 node 进程的当前工作目录解析相对路径。可以使用以下命令确认 cwd:

console.log(process.cwd());

node进程的cwd是从你调用node的地方决定的。

例如,如果您有以下文件结构:

/
└──projects/
   └──app/
      ├──js/
      │  └──dep.js
      ├──index.js
      └──test.txt

index.js 内容:

const fs = require('fs');
console.log(process.cwd());
console.log(fs.readFileSync('./test.txt'));
require('./js/dep.js');

dep.js 内容:

const fs = require('fs');
console.log(process.cwd());
console.log(fs.readFileSync('./test.txt'));

如果您导航到/projects/app 并运行node index.js,您会看到程序成功打印了两次 cwd 和 test.txt 的内容。这演示了 cwd 如何在程序使用的不同源文件中保持一致。

如果您导航到 /app 并运行 node app/index.js,您会看到程序崩溃并出现 ENOENT 错误。这演示了从不同位置启动程序如何改变 cwd。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-23
    • 1970-01-01
    相关资源
    最近更新 更多