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.on('death', function(worker) {
                console.log('worker ' + worker.pid + ' died');
    var server = http.createServer(function(request, response) {
    stream = fs.createWriteStream("nodejsCluster"+cluster.worker.id+".txt");
    stream.once('open', function(fd) {
    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);
  • 3
    \$\begingroup\$ Welcome to Code Review! It's recommended to choose a title that describes what your code does, rather than what you are looking for in a review. \$\endgroup\$ – Phrancis Feb 10 '15 at 5:32

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

Client sessions will just sit there hanging until you do that.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.