Asynchronous Operations In Node.js

Node.js is a JavaScript server-side framework. One of the things you can do easily with it is write a HTTP server.

a simple “Hello, world” server looks like:

http = require ('http');
http.createServer(function(request, response){
  response.write("Hello, world");
  response.end();
}).listen(8888);

Now, if you run the simple server and type ‘http://127.0.0.1:8888’ in the URL bar of your browser you’ll see the text “Hello, world” in the browser’s window.

I’m sure you’re going to use Node.js for things more complicated than “Hello, world” programs. This server is one process that receive a request and sends a response. Other servers may perform operations that take longer, and we don’t want an operation to block the server from performing other tasks, such as handling other requests.
Node.js allows you to performs those operation in a non-blocking manner by providing the developer with function that accept a callback function as their last parameter. Those function are performed in another thread, and call the callback function upon completion.

The example I want to show you is a code fragment for disk I/O opeerations:

fs=require('fs');

fs.open('a.txt','w', function(err, fd){
  if (err)
    throw err;
  buffer=new Buffer("some long text");
  bufferLen=buffer.length;
  bytesWrittenSoFar = 0;
  pos=0;
  (function writeIt(){
    console.log('Buffer Len ' + bufferLen + ', Bytes Written ' + bytesWrittenSoFar);
    fs.write(fd,buffer,bytesWrittenSoFar, bufferLen - bytesWrittenSoFar, null, function(err,writtenBytes){
      if (err)
        throw err;
      if (bytesWrittenSoFar == bufferLen){
        console.log('Done!');
      } else {
        bytesWrittenSoFar += writtenBytes;
        writeIt();
      }
    });
  })();
});

How Does It Work?

In this example you can see two asynchronous function:

  • ‘fs.open’, that opens the file, and as the file is open calls the callback function, its 3rd argument.
  • fs.write – that attempts to write the output, and then calls the function ‘writeIt’.

This callback functions are called upon completion of opening a file, or writing it. The completion may be successful or unsuccessful. If unsuccessful, error handling should take place.

The Function WriteIt

The function ‘writeIt’ is a function which is defined and immediately performed. This function is called asynchronously, and until all the data is written, it keeps calling itself. We cannot perform this task using a loop, because a loop will create threads running in parallel. Therefore we use “asynchronous recursion”.

File System function with a simpler syntax have the suffix ‘Sync’ at the end of their names. Those functions you would usually want to avoid, so instead of having the default names, they have a name with a suffix.

Learn more about how to program in Node.js here, and maybe purchase a tutorial with exercises.

Find documentation about Node.js modules and functions here.

Advertisements

One thought on “Asynchronous Operations In Node.js

  1. This is a message to the webmaster. Your website is missing out on at least 300 visitors per day. I have found a company which offers to dramatically increase your traffic to your website: http://www.example.com They offer 1,000 free visitors during their free trial period and I managed to get over 30,000 visitors per month using their services, you could also get lot more targeted visitors than you have now. Hope this helps 🙂 Take care.

Comments are closed.