gpt4 book ai didi

linux - 在 Node.JS 中引用相对于应用程序根目录的文件的正确方法

转载 作者:IT老高 更新时间:2023-10-28 22:08:55 25 4
gpt4 key购买 nike

我有一个在 AWS EC2 上的 Linux 上运行的 Node.JS 应用程序,它使用 fs 模块来读取 HTML 模板文件。这是应用程序的当前结构:

/server.js
/templates/my-template.html
/services/template-reading-service.js

HTML 模板将始终位于该位置,但是,模板阅读服务可能会移动到不同的位置(更深的子目录等)。从模板阅读服务中,我使用 fs.readFileSync()加载文件,如下所示:

var templateContent = fs.readFileSync('./templates/my-template.html', 'utf8');

这会引发以下错误:

Error: ENOENT, no such file or directory './templates/my-template.html'

我假设这是因为路径“./”解析到“/services/”目录而不是应用程序根目录。我也尝试将路径更改为“../templates/my-template.html”并且有效,但它似乎很脆弱,因为我想这只是相对于“向上一个目录”进行解析。如果我将 template-reading-service 移动到更深的子目录,那条路径就会中断。

那么,相对于应用程序的根目录引用文件的正确方法是什么?

最佳答案

试试

var templateContent = fs.readFileSync(path.join(__dirname, '../templates') + '/my-template.html', 'utf8');

关于linux - 在 Node.JS 中引用相对于应用程序根目录的文件的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13051961/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com