gpt4 book ai didi

node.js - Node/IO.js 需要项目根目录吗?

转载 作者:太空宇宙 更新时间:2023-11-04 02:25:58 25 4
gpt4 key购买 nike

假设我有一个像这样的项目结构:

root/
|
-- app.js
-- config.json
-- package.json
-- lib/
|
-- config/
|
-- config.js

此外,假设我想从 config.js 中读取根 config.json (以覆盖默认配置)。我可以执行以下操作:

const path = require('path');
let jsonConfig = {};
try {
let moduleDir = path.dirname(process.mainModule.filename);
jsonConfig = require(`${moduleDir}/config.json`);
} catch (e) {}

我的问题是,我应该吗? documentation states :

Alternate way to retrieve require.main. The difference is that if the main module changes at runtime, require.main might still refer to the original main module in modules that were required before the change occurred. Generally it's safe to assume that the two refer to the same module.

我不知道什么条件会导致我的主模块在运行时发生变化。我认为这将是我自己明确做的事情,但我对运行时的内部结构还不够熟悉,无法确定。

编辑以澄清:

我知道我可以使用相对路径,例如require('../../config.json')。但这使得日后重构/移动 lib/config/config.js 变得更加困难如果这是我最终要做的事情。因此我希望 require 相对于基本项目目录。

此配置也是特定于应用程序的。将其放入 node_modules 下的模块中并不是我想要做的事情。我只将 npm 托管依赖项放入 node_modules 中。

我的问题更多的是关于依赖 process.mainModule 可能引起的潜在意外问题,而不是关于 require 函数。

最佳答案

你可以像这样硬编码

require('../../config')

或者,您可以利用 Node 中的 node_modules 查找功能,并将 config.json 移动到 node_modules/config/index.json

root/
|
-- app.js
-- node_modules
|
-- config
|
-- package.json
-- index.json
-- package.json
-- lib/
|
-- config/
|
-- config.js

然后使用

require('config')

关于node.js - Node/IO.js 需要项目根目录吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30467514/

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