gpt4 book ai didi

javascript - 什么被认为是在 Node 模块内共享 "global"变量的好方法?

转载 作者:数据小太阳 更新时间:2023-10-29 05:35:26 33 4
gpt4 key购买 nike

如何在没有显式相对路径 (../../../lib..) 的情况下轻松引用模块中的其他目录?

我正在编写一个 Node 模块,我想在我的模块中重用一些全局的东西。
最基本的是——我想将模块的根路径设置为“全局”,这样我就可以轻松调用其他源,而无需使用大量相对路径 ../../ 之类的东西。它会导致代码困惑,如果项目结构发生变化,很容易出错或遗漏。

所以我看到了很多选项in that post和其他一些用于处理此类事情的库(例如提供根路径的模块 - app-module-pathrootpathrfr 等),但它们都引用基础项目/应用程序而不是模块其他人正在使用它。

设置一个全局变量是个坏主意,我知道环境变量也不是一个好主意。

这件事有好的做法吗?也许有些东西我还没有发现或听说过。

下面是我试图避免和寻找的示例:

// avoid things like that:

// ./lib/something/forthat/doit.js
var config = require('../../../config/project/type1/config.js');

// ./config/project/type1/config.js
module.exports = {
msg: 'hi'
};


// find somethings like that:
// when the root path/require can be found in every location of the module
// and is relative to my app and not the app using my module.

// ./lib/something/forthat/doit.js
var config = require(rootPath + 'config/project/type1/config.js');
// OR
var config = rootRequire('config/project/type1/config.js');
// OR anything else

// ./config/project/type1/config.js
module.exports = {
msg: 'hi'
};

最佳答案

要获取当前目录路径,您可以在 nodejs 项目的任何位置使用全局变量 __dirname。示例:console.log(__dirname) 将其写入项目中的任何文件,控制台会将当前目录路径打印为字符串。或者,您可以使用 express-session 模块;

var express = require('express');
var session = require('express-session');
var app = express();
app.use(session({myVar: 'abc'}));
app.get('/',function(req,res){
var sess = req.session;
console.log(sess);
});

关于javascript - 什么被认为是在 Node 模块内共享 "global"变量的好方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35406141/

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