Node JS - 通过引用其他文件传递 Javascript 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7905294/
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
Node JS - Passing Javascript object by reference to other files
提问by Mark Gia Bao Nguyen
I have defined an http server by requiring as follows:
我通过如下要求定义了一个 http 服务器:
var http = require('http');
function onRequest(request, response) {
console.log("Request" + request);
console.log("Reponse" + response);
}
http.createServer(onRequest).listen(8080);
I would like to pass the http object to a JS class (in a separate file) where I load external modules that are specific to my application.
我想将 http 对象传递给一个 JS 类(在一个单独的文件中),在那里我加载特定于我的应用程序的外部模块。
Any suggestions on how would I do this?
关于我将如何做到这一点的任何建议?
Thanks, Mark
谢谢,马克
回答by Teemu Ikonen
You don't need to pass the http object, because you can require it again in other modules. Node.js will return the same object from cache.
您不需要传递 http 对象,因为您可以在其他模块中再次使用它。Node.js 将从缓存中返回相同的对象。
If you need to pass object instance to module, one somewhat dangerous option is to define it as global (without var keyword). It will be visible in other modules.
如果您需要将对象实例传递给模块,一个有点危险的选择是将其定义为全局(不带 var 关键字)。它将在其他模块中可见。
Safer alternative is to define module like this
更安全的选择是像这样定义模块
// somelib.js
module.exports = function( arg ) {
return {
myfunc: function() { console.log(arg); }
}
};
And import it like this
然后像这样导入
var arg = 'Hello'
var somelib = require('./somelib')( arg );
somelib.myfunc() // outputs 'Hello'.
回答by Nican
Yes, take a look at how to make modules: http://nodejs.org/docs/v0.4.12/api/modules.html
是的,看看如何制作模块:http: //nodejs.org/docs/v0.4.12/api/modules.html
Every module has a special object called exports
that will be exported when other modules include it.
每个模块都有一个名为的特殊对象exports
,当其他模块包含它时将导出该对象。
For example, suppose your example code is called app.js
, you add the line exports.http = http
and in another javascript file in the same folder, include it with var app = require("./app.js")
, and you can have access to http with app.http
.
例如,假设您的示例代码名为app.js
,您exports.http = http
在同一文件夹中的另一个 javascript 文件中添加该行并使用将其包含在内var app = require("./app.js")
,然后您就可以使用app.http
.