【问题标题】:Relative path readFile error ENOENT: no such file相对路径 readFile 错误 ENOENT: 没有这样的文件
【发布时间】:2016-11-18 14:01:48
【问题描述】:

我有一个服务器文件,它根据我构建的restify API 向用户发送电子邮件。该文件位于/lib 目录下。当该文件mail_helper.js 尝试读取文件./email_templates/default-inline.html 时,它会失败。它试图从节点应用程序的root 中而不是在lib 目录中查找email_template 文件。文件夹结构如下所示:

- root
   - package.json
   - index.js (requires lib/mail_helper.js)
   - lib
      - mail_helper.js (reads file ./email_templates/default-inline.html)
      - email_templates
         - default-inline.html

从根目录运行node index.js会抛出错误:

错误:ENOENT:没有这样的文件或目录,打开 'my-local-path\root\email-templates\default-inline.html'

如何正确引用相对路径以避免这种情况?

【问题讨论】:

  • @Keith 成功了!但是我放了那么多地方。您能否在答案中添加一些代码并解释 __dirname 的作用?

标签: javascript node.js relative-path


【解决方案1】:

正如 Keith 在 cmets 中提到的,

相对路径应该这样写:

path.join(__dirname, 'email_templates', 'default-inline.html')

在我的模块中的所有位置替换它之后,这个,工作并修复了我的所有错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-07
    • 2019-03-09
    • 2017-12-28
    • 2022-01-16
    • 2021-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多