Node.js – Asynchronous Programming

node Programming

Overview

In this section, I discuss a fundamental concept of Node called Asynchronous programming and how it differs from synchronous programming. The syntax is slightly different and examples will be provided for demonstration differences between both types of programming models. Asynchronous programming allows Node to execute callbacks in a single thread, thus improved performance and reduced I / O latency between requests. To become more efficient at programming with Node, you need a good an understanding of asynchronous programming and what Node offers to help you with your asynchronous code control threads.
Most programmers are familiar with synchronous programming and this writing code that does one thing after another. For example, take the following the code:

var fs = require('fs');
var content = fs.readFileSync('simpleserver1.js','utf-8');
console.log('File content: ');
console.log(content);

The above code outputs the code of a simple web server to the console. The code is executed sequentially executing each line after the next. Next line not executed until the previous line has finished executing. Although this is normal, and if was the file in this example really large and took a few minutes to read? How can any other operations performed while this code is running or a long running operation? Make that we are using the concept of function callbacks. The code below shows how it should be written to use an asynchronous callback function:

var fs = require('fs');
fs.readFile('simpleserver1.js','utf-8', function(err,data){
if (err) {
throw err;
}
console.log("I am executed from the file finishes reading"); console.log('File content: ');
console.log(data);
});

Note that in the above example the line I am … is executed as a file read, which allows us to perform operations, while the main read operation the file is also executed. If you are working with .NET this might are similar to a using statement to make the same asynchronous calls. You can also have callbacks with built-in callback functions, but this often results in the script is called spaghetti callback code. To solve the problem of braking callbacks, Node has a module called Async to handle asynchronous callbacks flow.