最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

node.js - Node JS - Passing Javascript object by reference to other files - Stack Overflow

programmeradmin1浏览0评论

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

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?

Thanks, Mark

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

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?

Thanks, Mark

Share Improve this question asked Oct 26, 2011 at 15:50 Mark NguyenMark Nguyen 7,44810 gold badges33 silver badges42 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 15

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.

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.

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'.

Yes, take a look at how to make modules: 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.

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.

发布评论

评论列表(0)

  1. 暂无评论