nextTick

process.nextTick(callback)

On the next loop around the event loop call this callback. This is not a simple alias to setTimeout(fn, 0), it’s much more efficient. nextTick is not called continually, and can be used to defer processing of something. An example of this would be to defer logging a client request until after the client has been served data, so as to reduce latency from hitting the filesystem:

function LogMessage(message) {
  fs.write(logfile, message);
}

var http = require('http');
var fs = require('fs');
var server;
var logfile;

function StartServer() {
  console.log("Starting server...");

  fs.open('http.log', 'a', function(err, fd) {

    if(err) {
      console.error("Could not open logfile: %s", err);
    }
    else {
      logfile = fd;
    }

    // Initalizations such as reading the config file, etc.
    server = http.createServer(function (req, res) {

    process.nextTick(function() {
      LogMessage("[" + new Date().toUTCString() + " " + req.connection.remoteAddress + "] " + req.method + " " + req.url + "\n");
    });

    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World\n');

    });

    try {
      server.listen(1337, "127.0.0.1"); 
    }
    catch(listen_error) {
      console.error("Error: [%s] Call: [%s]", listen_error.message, listen_error.syscall);
      process.exit(1);
    }

  });
}

function StopServer(shutdown) {
  console.log("Stopping server...");

  fs.close(logfile,function(){
    if(server) {
      server.close();
      if(shutdown) {
        console.log("Exiting server process.");
        process.exit();
      }
    }
  });
}

process.on("SIGHUP", function(){
  console.log("Received SIGHUP, restarting server...");
  StopServer();
  StartServer();
});

process.on("SIGINT", function(){
  console.log("Received SIGINT, cleaning up...");
  StopServer();
});

process.on("SIGTERM", function(){
  console.log("Received SIGTERM, cleaning up...");
  StopServer();
});

StartServer();

A sample logfile:

[Tue, 31 May 2011 11:21:47 GMT 127.0.0.1] GET /
[Tue, 31 May 2011 11:21:48 GMT 127.0.0.1] GET /
[Tue, 31 May 2011 11:21:49 GMT 127.0.0.1] GET /
[Tue, 31 May 2011 11:21:52 GMT 127.0.0.1] GET /

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s