Node JS - Passing a Javascript Object by Link to Other Files

I defined the http server by doing the following:

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 the JS class (in a separate file), where I load external modules specific to my application.

Any suggestions on how I can do this?

Thanks Mark

+4
source share
2 answers

Yes, see how to create modules: http://nodejs.org/docs/v0.4.12/api/modules.html

Each module has a special object called exports , which will be exported when other modules are added to it.

For example, suppose your sample code is called app.js , you add the line exports.http = http and to another javascript file in the same folder, include it with var app = require("./app.js") , and you can access http using app.http .

+6
source

You do not need to pass the http object because you can request it again in other modules. Node.js will return the same object from the cache.

If you need to pass an instance of an object to a module, one of the dangerous ways is to define it as global (without the var keyword). It will be visible in other modules.

A safer alternative is to define a 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'. 
+13
source

All Articles