Node JS - 通过引用传递Javascript对象到其他文件 [英] Node JS - Passing Javascript object by reference to other files

查看:78
本文介绍了Node JS - 通过引用传递Javascript对象到其他文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经通过要求如下定义了一个http服务器:

I have defined an http server by requiring as follows:

var http = require('http');

function onRequest(request, response) {
    console.log("Request" + request);
    console.log("Reponse" + response);
}

http.createServer(onRequest).listen(8080);

我想将http对象传递给我加载的JS类(在单独的文件中)特定于我的应用程序的外部模块。

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.

关于我该如何做的任何建议?

Any suggestions on how would I do this?

谢谢,
Mark

Thanks, Mark

推荐答案

是的,看看如何制作模块: http://nodejs.org/docs/v0.4.12/api/modules.html

Yes, take a look at how to make modules: http://nodejs.org/docs/v0.4.12/api/modules.html

每个模块都有一个名为 exports 的特殊对象,当其他模块包含它时,它将被导出。

Every module has a special object called exports that will be exported when other modules include it.

例如,假设您的示例代码名为 app.js ,您在 exports.http = http 中添加行并在另一个javascript文件中在同一文件夹中,将其包含在 var app = require(./ app.js)中,您可以使用 app访问http .http

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.

这篇关于Node JS - 通过引用传递Javascript对象到其他文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆