我有一个Node.JS应用程序在AWS EC2的Linux上运行,它使用fs模块读取HTML模板文件。以下是应用程序的当前结构:
/server.js
/模板/my-template.html
/服务/template-reading-service.js
HTML模板将始终位于该位置,但是,模板读取服务可能会从模板读取服务中移动到不同的位置(更深的子目录等),我使用fs.readFileSync()加载文件,如下所示:
var templateContent=fs.readFileSync('./templates/my template.html','utf8');
这会引发以下错误:
错误:enoint,没有这样的文件或目录。“/templates/my template.html”
我假设这是因为路径“/”解析为“/services/”目录,而不是应用程序根目录。我还尝试将路径更改为“../templates/my template.html”,这很有效,但它似乎很脆弱,因为我认为这只是相对于“上一个目录”进行解析。如果我将模板读取服务移动到更深的子目录,该路径将中断
那么,相对于应用程序的根引用文件的正确方法是什么
试一试
var templateContent=fs.readFileSync(path.join(uu dirname,“../templates')+”/my template.html,“'utf8');