在节点模块内共享“全局”variables是一种很好的方法吗?

我怎样才能轻松地引用我的模块中的其他目录没有明确的相对path( ../../../lib.. )?

我正在编写一个节点模块,我想在模块中重用一些全局的东西。
最基本的 – 我想设置模块的根path为“全局”,所以我可以很容易地调用其他来源,而不使用大量的相对path../../和类似的东西。 这会导致代码混乱,如果项目结构发生变化,很容易出错或错过。

所以我在这篇 文章和其他一些库中看到了很多选项来处理这些事情(比如给出根path的模块 – app-module-path , rootpath , rfr等),但是他们都指向一个基础项目/应用程序,而不是其他人正在使用的模块。

设置全局是一个坏主意,我明白,一个环境variables也不是一个好主意。

对这件事情有一个好的做法吗? 也许有些事我没有find或听说过。

以下是我想要避免的以及我正在寻找的一个示例:

 // 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' }; 

要获取当前的目录path,可以使用全局variables__dirname ,在nodejs项目中的任何位置。 例如: console.log(__dirname)将其写入到项目中的任何文件中,控制台将以stringforms打印当前目录path。 或者,您可以使用快速会话模块;

 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); }); 

首先,相对path根本不会造成混淆。 相反,你可以称它杂乱(如果你想),它被认为是最好的做法。 但是我也能理解你。 你不喜欢非常混乱的代码。 所以对于这种情况,你应该把这个部分/代码作为静态内容。 因此,您可以轻松地访问它,并提供一个非常简单的login拖放path。 但请记住,这是相对path服务的替代scheme。