Reputation: 5358
How to implement a module say 'test' which exposes two functions getter and setter to get and set its member data in nodejs?
The trick is data set via setter from a module say 'a' over 'test' should be accessible to module 'b' via getter of 'test'
Scenario is, once we register req and res objects of http request to 'test' from index, it should be accessible to all other modules across the app just by declaring require('test')
Is this possible in nodejs?
Upvotes: 1
Views: 449
Reputation: 63683
You cannot achieve that, even if you set a global variable because req
and res
are accessible on each page request (so setting them as global vars would make a race condition occur).
The only way to achieve this is to pass req and res as parameters to that module.
Example:
app.js
var http = require('http');
http.createServer(function (req, res) {
require('./sample')(req, res);
}).listen(1337, "127.0.0.1");
sample.js
module.exports = function (req, res) {
// do stuff with req and res here
}
Upvotes: 2