相对路径 readFile 错误 ENOENT: 没有那个文件

Relative path readFile error ENOENT: no such file

我有一个服务器文件,它根据我构建的 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 从根目录抛出错误:

Error: ENOENT: no such file or directory, open 'my-local-path\root\email-templates\default-inline.html'

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

正如 Keith 在评论中提到的,

相对路径应该这样写:

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

在我的模块中的所有地方替换它后,这个有效并修复了我的所有错误。