node.js app.js 中的全局变量可以在路由中访问吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9765215/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Global Variable in app.js accessible in routes?
提问by Technupe
How do i set a variable in app.jsand have it be available in all the routes, atleast in the index.jsfile located in routes. using the express framework and node.js
我如何设置一个变量app.js并让它在所有路由中都可用,至少在index.js位于路由中的文件中可用。使用 express 框架和node.js
采纳答案by Jesse Fulton
To make a global variable, just declare it without the varkeyword. (Generally speaking this isn't best practice, but in some cases it can be useful - just be careful as it will make the variable available everywhere.)
要创建一个全局变量,只需在没有var关键字的情况下声明它。(一般来说,这不是最佳实践,但在某些情况下它可能很有用 - 请小心,因为它会使变量随处可用。)
Here's an example from visionmedia/screenshot-app
这是来自visionmedia/screenshot-app的示例
file app.js:
文件app.js:
/**
* Module dependencies.
*/
var express = require('express')
, stylus = require('stylus')
, redis = require('redis')
, http = require('http');
app = express();
//... require() route files
file routes/main.js
文件路由/main.js
//we can now access 'app' without redeclaring it or passing it in...
/*
* GET home page.
*/
app.get('/', function(req, res, next){
res.render('index');
});
//...
回答by Mandy
It is actually very easy to do this using the "set" and "get" methods available on an express object.
使用 express 对象上可用的“set”和“get”方法实际上很容易做到这一点。
Example as follows, say you have a variable called config with your configuration related stuff that you want to be available in other places:
示例如下,假设您有一个名为 config 的变量,其中包含您希望在其他地方可用的配置相关内容:
In app.js:
在 app.js 中:
var config = require('./config');
app.configure(function() {
...
app.set('config', config);
...
}
In routes/index.js
在路由/index.js
exports.index = function(req, res){
var config = req.app.get('config');
// config is now available
...
}
回答by Ali
回答by Vadim Baryshev
To declare a global variable you need do use globalobject. Like global.yourVariableName. But it is not a true way. To share variables between modules try to use injection style like
要声明一个全局变量,您需要使用全局对象。像 global.yourVariableName。但这不是真正的方法。要在模块之间共享变量,请尝试使用注入样式,例如
someModule.js:
someModule.js:
module.exports = function(injectedVariable) {
return {
somePublicMethod: function() {
},
anotherPublicMethod: function() {
},
};
};
app.js
应用程序.js
var someModule = require('./someModule')(someSharedVariable);
Or you may use surrogate object to do that. Like hub.
或者您可以使用代理对象来做到这一点。像集线器。
someModule.js:
someModule.js:
var hub = require('hub');
module.somePublicMethod = function() {
// We can use hub.db here
};
module.anotherPublicMethod = function() {
};
app.js
应用程序.js
var hub = require('hub');
hub.db = dbConnection;
var someModule = require('./someModule');
回答by Victor Cruz
Here are explain well, in short:
这里有很好的解释,简而言之:
http://www.hacksparrow.com/global-variables-in-node-js.html
http://www.hacksparrow.com/global-variables-in-node-js.html
So you are working with a set of Node modules, maybe a framework like Express.js, and suddenly feel the need to make some variables global. How do you make variables global in Node.js?
所以你正在使用一组 Node 模块,可能是一个像 Express.js 这样的框架,突然觉得需要让一些变量成为全局变量。你如何在 Node.js 中使变量成为全局变量?
The most common advice to this one is to either "declare the variable without the var keyword" or "add the variable to the global object" or "add the variable to the GLOBAL object". Which one do you use?
对此最常见的建议是“声明变量而不使用 var 关键字”或“将变量添加到全局对象”或“将变量添加到全局对象”。你用哪一种?
First off, let's analyze the global object. Open a terminal, start a Node REPL (prompt).
首先,让我们分析一下全局对象。打开终端,启动 Node REPL(提示)。
> global.name
undefined
> global.name = 'El Capitan'
> global.name
'El Capitan'
> GLOBAL.name
'El Capitan'
> delete global.name
true
> GLOBAL.name
undefined
> name = 'El Capitan'
'El Capitan'
> global.name
'El Capitan'
> GLOBAL.name
'El Capitan'
> var name = 'Sparrow'
undefined
> global.name
'Sparrow'
回答by John Gordon
This was a helpful question, but could be more so by giving actual code examples. Even the linked article does not actually show an implementation. I, therefore, humbly submit:
这是一个有用的问题,但通过提供实际的代码示例可能会更有用。即使链接的文章实际上也没有显示实现。因此,我谦虚地提出:
In your app.jsfile, the top of the file:
在您的app.js文件中,文件的顶部:
var express = require('express')
, http = require('http')
, path = require('path');
app = express(); //IMPORTANT! define the global app variable prior to requiring routes!
var routes = require('./routes');
app.js will not have anyreference to app.get()method. Leave these to be defined in the individual routes files.
app.js 不会有任何app.get()方法引用。将这些保留在各个路由文件中定义。
routes/index.js:
routes/index.js:
require('./main');
require('./users');
and finally, an actual routes file, routes/main.js:
最后,一个实际的路由文件,routes/main.js:
function index (request, response) {
response.render('index', { title: 'Express' });
}
app.get('/',index); // <-- define the routes here now, thanks to the global app variable
回答by Will Stern
My preferred way is to use circular dependencies*, which node supports
我的首选方法是使用循环依赖*,该节点支持
- in app.js define
var app = module.exports = express();as your first order of business - Now any module required after the fact can
var app = require('./app')to access it
- 在 app.js 中定义
var app = module.exports = express();为您的第一个业务订单 - 现在任何事后需要的模块都
var app = require('./app')可以访问它
应用程序.js
var express = require('express');
var app = module.exports = express(); //now app.js can be required to bring app into any file
//some app/middleware, config, setup, etc, including app.use(app.router)
require('./routes'); //module.exports must be defined before this line
路线/ index.js
var app = require('./app');
app.get('/', function(req, res, next) {
res.render('index');
});
//require in some other route files...each of which requires app independently
require('./user');
require('./blog');
回答by Shaman
the easiest way is to declare a global variable in your app.js, early on:
最简单的方法是尽早在 app.js 中声明一个全局变量:
global.mySpecialVariable = "something"
then in any routes you can get it:
然后在任何路线中你都可以得到它:
console.log(mySpecialVariable)
回答by Charlie Schliesser
As others have already shared, app.set('config', config)is great for this. I just wanted to add something that I didn't see in existing answers that is quite important. A Node.js instance is shared across all requests, so while it may be very practical to share some configor routerobject globally, storing runtime data globally will be available across requests and users. Consider this very simple example:
正如其他人已经分享的那样,app.set('config', config)这很棒。我只是想添加一些我在现有答案中没有看到的非常重要的东西。Node.js 实例在所有请求之间共享,因此虽然全局共享某些config或router对象可能非常实用,但全局存储运行时数据将跨请求和用户可用。考虑这个非常简单的例子:
var express = require('express');
var app = express();
app.get('/foo', function(req, res) {
app.set('message', "Welcome to foo!");
res.send(app.get('message'));
});
app.get('/bar', function(req, res) {
app.set('message', "Welcome to bar!");
// some long running async function
var foo = function() {
res.send(app.get('message'));
};
setTimeout(foo, 1000);
});
app.listen(3000);
If you visit /barand another request hits /foo, your message will be "Welcome to foo!". This is a silly example, but it gets the point across.
如果您访问/bar并命中另一个请求/foo,您的消息将是“欢迎来到 foo!”。这是一个愚蠢的例子,但它明白了这一点。
There are some interesting points about this at Why do different node.js sessions share variables?.
有在这个一些有趣的点,为什么不同的node.js会话变量共享?.
回答by Amar Dev
I solved the same problem, but I had to write more code.
I created a server.jsfile, that uses express to register routes.
It exposes a function,register, that can be used by other modules to register their own routes.
It also exposes a function, startServer, to start listening to a port
我解决了同样的问题,但我不得不写更多的代码。我创建了一个server.js文件,该文件使用 express 来注册路由。它公开了一个函数,register,其他模块可以使用它来注册自己的路由。它还公开了一个函数 ,startServer以开始侦听端口
server.js
const express = require('express');
const app = express();
const register = (path,method,callback) => methodCalled(path, method, callback)
const methodCalled = (path, method, cb) => {
switch (method) {
case 'get':
app.get(path, (req, res) => cb(req, res))
break;
...
...
default:
console.log("there has been an error");
}
}
const startServer = (port) => app.listen(port, () => {console.log(`successfully started at ${port}`)})
module.exports = {
register,
startServer
}
In another module, use this file to create a route.
在另一个模块中,使用此文件创建路由。
help.js
const app = require('../server');
const registerHelp = () => {
app.register('/help','get',(req, res) => {
res.send("This is the help section")
}),
app.register('/help','post',(req, res) => {
res.send("This is the help section")
})}
module.exports = {
registerHelp
}
In the main file, bootstrap both.
在主文件中,引导两者。
app.js
require('./server').startServer(7000)
require('./web/help').registerHelp()

