Reputation: 35
I'm using restify to write a basic REST API framework in node. To support this, I have several helper objects that I export and require.
I'm having trouble understanding how to require these objects in such a way that each incoming HTTP request uses a unique instance of the helper object. As it is, I require() the module inside the scope of the GET request, but I have a feeling that's not the best practice. For example:
helper.js
var helper = function(){
this.foo = new Date().getTime();
return this;
};
helper.prototype.test = function(){
return new Date().getTime();
};
module.exports = new helper();
main.js
app.get("/", function(req, res){
var helper = require("./helper");
helper.test();
});
helper.test() works: each incoming request has it's own scoped instance of helper. If I require the helper file outside of the request scope, then data within the helper object is shared between requests, because of the way node caches the object of a required file.
However, in this case, helper.foo is the same for each call, presumably because the require() call is receiving 1 instance via the "new" keyword.
I came across this issue when I had a helper function that used a random string to name a file, but because I had declared it like (below), all files were named the same.
helper.prototype.fileName = random(10) + ".json";
Does requiring files within the scope of a request have any negative consequences? I would imagine that when dealing with high frequency traffic, it would not be ideal to be requesting files for each call.
What are the best practices for requiring / exporting modules while considering multiple incoming HTTP requests via express or restify? Should I just make sure the helpers I'm writing don't deal with these edge cases?
Upvotes: 1
Views: 2394
Reputation: 2673
Okay, so first it would be good to go over what require does. Fred K. Schott describes this really well thenodeway.io. So essentially, the require function:
So after you require a file to begin with, there is no additional overhead to require it again.
Secondly, your question is a general javascript question. To achieve what you are wanting to achieve change your files to do this:
helper.js
var helper = function(){
this.foo = new Date().getTime();
this.fileName = random(10) + ".json";
return this;
};
helper.prototype.test = function(){
return new Date().getTime();
};
module.exports = helper;
main.js
var Helper = require("./helper");
app.get("/", function(req, res){
var helper = new Helper();
helper.test()
});
That way helper is always unique for each request.
So, try to use modules often when you are segmenting your code. They only add initial overhead, and do not inherently affect performance for heavy traffic.
Upvotes: 2