HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Saving away URL query parameters in an analytics application

Submitted by: @import:stackexchange-codereview··
0
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:

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.