简体   繁体   English

如何解析node_modules中文件的路径

[英]How to resolve path to a file within node_modules

Problem loading a file using relative path when my node app is initialised using a another node app 使用另一个节点应用程序初始化我的节点应用程序时,使用相对路径加载文件时出现问题

I have created an npm which relies on a file stored relative to project root. 我创建了一个npm,它依赖于相对于项目根目录存储的文件。 something like this 像这样的东西

index.js
- res 
  - config.json

Now I read the config.json using following code 现在我使用以下代码阅读config.json

const pathToConfig =  path.resolve(__dirname, '../res/config.json')

This works great locally. 这在本地效果很好。
But in my prod setup this app is initialised by another node app. 但是在我的产品设置中,此应用是由另一个节点应用初始化的。
And __dirname resolves to root of that app so all my logic to find config.json get messed up. __dirname解析为该应用程序的根目录,因此我所有用于查找config.json的逻辑都被弄乱了。
Is there any way I can read the file without worrying about how node app was initialised? 有什么方法可以读取文件而无需担心节点应用程序如何初始化?

Have you tried the command process.cwd()? 您是否尝试过命令process.cwd()? It is almost the same as __dirname but does differ slightly. 它与__dirname几乎相同,但略有不同。

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

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