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");

Now, if you run the simple server and type ‘’ 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');'a.txt','w', function(err, fd){
  if (err)
    throw err;
  buffer=new Buffer("some long text");
  bytesWrittenSoFar = 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){
      } else {
        bytesWrittenSoFar += writtenBytes;

How Does It Work?

In this example you can see two asynchronous function:

  • ‘’, 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.