patternjavascriptMinor
Saving away URL query parameters in an analytics application
Viewed 0 times
awayapplicationquerysavingparametersurlanalytics
Problem
We are trying to use NodeJS for analytics. The following code gets the parameter from a URL and dumps it into a flat file. Is there any way to optimize it to get better response time?
var http = require("http");
var url = require("url");
var cluster = require('cluster');
var fs = require('fs');
var numCPUs = require('os').cpus().length;
var stream = [];
if (cluster.isMaster) {
for (var i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on('death', function(worker) {
console.log('worker ' + worker.pid + ' died');
});
}
else{
var server = http.createServer(function(request, response) {
response.end();
});
stream = fs.createWriteStream("nodejsCluster"+cluster.worker.id+".txt");
stream.once('open', function(fd) {
server.listen(8084);
});
server.on('request', function(request, response){
var parsedUrl = url.parse(request.url, true, true);
var queryAsObject = parsedUrl.query;
stream.write( ( new Date() )+'This is the content to write into file '+queryAsObject.test+"\n");
});
console.log("Server is listening"+cluster.worker.id);
}Solution
Your server sets up a cluster, then listens for requests. It parses a parameter from the request URL, and writes it to file.
For performance reasons, that write to file should be asyncrhonous. Currently your client has to wait for your log to write before the client continues.... but, here's the real flaw in your code....
... you do not send a response at all to the client!
You need to actually process the response by sending a status code, and ending the communication:
Client sessions will just sit there hanging until you do that.
For performance reasons, that write to file should be asyncrhonous. Currently your client has to wait for your log to write before the client continues.... but, here's the real flaw in your code....
... you do not send a response at all to the client!
You need to actually process the response by sending a status code, and ending the communication:
response.writeHeader(200); // success
response.end();Client sessions will just sit there hanging until you do that.
Code Snippets
response.writeHeader(200); // success
response.end();Context
StackExchange Code Review Q#80119, answer score: 2
Revisions (0)
No revisions yet.