Subscribe via RSS Feed

Node.js Synchronous and Asynchronous Functions

December 10, 2013 0 Comments

In node.js platform, as the non-blocking programming model is followed as practice, all most all of the functions in the node.js modules are primarily asynchronous in nature. It means, the code block within the function will be mostly non-blocking to the end user and user will not ne prevented to perform different actions for various sub-processes.

Still we have synchronous counter part of the functions which are present in node.js modules.

Here is a typical example for  synchronous and asynchronous functions for the file system module for Node.js.

Asynchronous function for readfile -

var filesystem = require("fs");

filesystem.readFile("myfirstexample.txt", "utf8", function(error, data) {

In the above function file system module takes file name and pass the data of the file as reference to the callback handler of an anonymous function. Then this file system object will remain ready for performing any other file system operation handling task.

Whenever the full read of the file is complete, the callback function log the content of the file to the console. Here the application performance will not hamper in the system.
Synchronous function for readfile -

var filesystem  = require("fs");
var data = filesystem.readFileSync("myfirstexample.txt", "utf8");


Here the function readFileSync completely read the contents from the file to the memory and then go to print the data in console. So the calling of the code block is synchronous here and without full content read, it will not go for the next line.

Now in a situation of active server, where most of the interaction will be done by end users, the second type of operation will impact the application performance as this is a blocking code model. Where as the first type of operation will give a more improved performance to the user because of the non-blocking code in nature.

We will discuss various other aspects of node.js programming model in future posts.

So stay tuned and comment here with node.js feature discussion and useful links.