I have a Node.js HTTP server running which goes like this (simplified):
http = require('http');
help = require('./modules/help').run;
router = require('./modules/router').run;
m = {something: require('./modules/something')};
var server = http.createServer(router).listen(8001);
"help" is a set of functions-helpers, for example:
module.exports.run = {
joinObjects: function(obj1, obj2) {
for (var prop in obj2) {
obj1[prop] = obj2[prop];
}
return obj1;
}
}
"router" handles the request (passes it further down and handles response to the client):
module.exports.run = function(req, res) {
var urlPath = url.parse(req.url).pathname;
switch(urlPath) {
case '/something':
requestHandler(req, res, 'something');
break;
...
}
function requestHandler(req, res, handler) {
var data = '';
req.on('data', function(chunk) {
data += chunk;
}
req.on('end', function() {
m[handler].run(req, data, function(response) {
response.headers = help.joinObjects(config.responseHeaders, response.headers);
res.writeHead(response.code, response.headers);
res.end(response.data);
});
}
}
}
The "handler" module/function runs the callback function and passes the response (code, headers and data) to it. The callback function then merges headers with a set of default headers that are set in the config file.
THE ISSUE: When there are two connections calling help.joinObjects()
at the same time (that's my guess), response.headers
property collides with the one of another user/connection and returns bad data. If I comment out the line that does the merging, this does not occur.
THE QUESTION: What's wrong with my approach to the "help" module? There is some kind of scope issue that I do not understand here.
As lazyhammer pointed out, the problem was the order in which I passed objects into the helper function: help.joinObjects(config.responseHeaders, response.headers)
.
Javascript passes variables by reference, so every time help.joinObjects()
is called, it overwrites the config property instead of the user-specific object.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.