简体   繁体   English

相对路径readFile错误ENOENT:没有这样的文件

[英]Relative path readFile error ENOENT: no such file

I have a server file which sends out emails to user based on the restify API I have built. 我有一个服务器文件,该文件根据我构建的restify API向用户发送电子邮件。 That file is under /lib directory. 该文件在/lib目录下。 And when that file mail_helper.js tries to read the file ./email_templates/default-inline.html it fails. 并且当该文件mail_helper.js尝试读取文件./email_templates/default-inline.html它将失败。 It is trying to find email_template file from the root of the node app instead of inside lib directory. 它正在尝试从节点应用程序的root目录而不是在lib目录中查找email_template文件。 The folder structure looks like this: 文件夹结构如下所示:

- 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

Running node index.js from the root directory throws the error: 从根目录运行node index.js会引发错误:

Error: ENOENT: no such file or directory, open 'my-local-path\\root\\email-templates\\default-inline.html' 错误:ENOENT:没有此类文件或目录,请打开“ my-local-path \\ root \\ email-templates \\ default-inline.html”

How can I reference relative path properly to avoid this situation? 如何正确引用相对路径以避免这种情况?

As mentioned in the comments by Keith, 正如Keith的评论中所述,

Relative path should be written like this: 相对路径应这样写:

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

This, worked and fix all of my errors after replacing this at all the places in my module. 在模块中的所有位置都将其替换后,可以解决并修复所有错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM