Mark Gia Bao Nguyen Mark Gia Bao Nguyen - 8 days ago 4x
Javascript Question

Node JS - Passing Javascript object by reference to other files

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


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?



Yes, take a look at how to make modules:

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.