未加星标

Learn the Concept of Callback in Node.JS

字体大小 | |
[前端(javascript) 所属分类 前端(javascript) | 发布者 店小二05 | 时间 2017 | 作者 红领巾 ] 0人收藏点击收藏

Learn the Concept of Callback in Node.JS

In this article, we are going to discuss the callback feature in Node.JS. Callback can be defined as an event which is invoked or called immediately after the completion of a particular task as desired. We will understand this with the help of two examples i.e. blocking and non-blocking calls.

Introduction to Callback

We are familiar with the concept of functions which are associated with various programming languages. Callback is similar to a function but it operates asynchronously. In other words, the callback function is always called immediately after the completion of an agreed task. In Node.js, almost all the APIs of Node are coded in such a manner that these will support callbacks. Let’s understand the callback function with the help of the following example.

Example of the Blocking Code

Here, we are going to write a Node.js code in order to read a text file ‘inputData.txt’ and display the data on the console.

Below is the content of the text file.

‘inputData.txt’

Hello! Welcometo Eduonixtutorialfor Node.js

Blocking Code (‘BlockingCode.js’)

This is a js file with the following lines of code.

var fileSystem = require("fs"); var filedata = fileSystem.readFileSync('inputData.txt'); console.log(filedata.toString()); console.log ("Program has successfully ended!"); Explanation of code and the callback concept Firstly, we import the required module by using the required directive “fs” in order to load the “fs” module and store the returned “fs” instance into a fileSystem variable as shown above. Next, we invoke ‘fileSystem.readFileSync (‘inputData.txt’)’ method to read ‘inputData.txt’ file synchronously into filedata variable. Next, we convert the file data into a string by using the ‘toString ()’ method and logging it on to the console. Lastly, we log a predefined message ‘Program has successfully ended!’ on to the console.

Here, the function reads a file and returns the control immediately to the execution environment in order to make the environment available for the execution of the next instruction. Once I/O operation is completed, the callback function will be invoked in order to pass the content of the file as a parameter. Thus, in this scenario we can observe that there is blocking or wait for I/O on file before proceeding to the next instruction in the program.

Output

When we execute the code present in the ‘BlockingCode.js’ file by using the node command, we can observe the following output.

C:\odesk\AbhishekThakur\NodeJS\CallbackNodeJSApplication>nodeBlockingCode.js Hello! Welcometo Eduonixtutorialfor Node.js Programhassuccessfullyended! C:\odesk\AbhishekThakur\NodeJS\CallbackNodeJSApplication>
Learn the Concept of Callback in Node.JS

Example on the Non-Blocking Code

‘ inputData.txt ‘ file has the following content: Hello! Welcometo Eduonixtutorialfor Node.js

Blocking Code (‘NonBlockingCode.js’)

This is a js file with the following lines of code.

var fileSystem = require("fs"); fileSystem.readFile('inputData.txt', function(error, filedata) { if (error){ return console.error(error); } console.log(filedata.toString()); }); console.log("Program has successfully ended"); Explanation of code and the callback concept Firstly, we import the required module by using the required directive “fs” in order to load the “fs” module and store the returned “fs” instance into a fileSystem variable as shown above. Next, we invoke ‘fileSystem.readFile (‘inputData.txt’, function (error, filedata) {}’ method to read ‘inputData.txt’ file into filedata variable. In this case, we are checking on the error condition in order to log the error details. Next, we convert the file data into a string by using the ‘toString ()’ method and log it on to the console. Lastly, we log a predefined message ‘Program has successfully ended!’ on to the console.

Here, the program does not wait sequentially to read a file and then execute the next instruction but it executes the next instruction and proceeds to print “Program has successfully ended” on the console before logging the file contents on to the console. Therefore, the program is reading the file ‘inputData.txt’ simultaneously without blocking. Such feature make Node.js very scalable in a manner that it permits the execution of large requests without making any function to wait before returning the result.

Output

When we execute the code present in the ‘NonBlockingCode.js’ file by using the node command, we can observe the following output.

C:\odesk\AbhishekThakur\NodeJS\CallbackNodeJSApplication>nodeNonBlockingCode.js Programhassuccessfullyended Hello! Welcometo Eduonixtutorialfor Node.js C:\odesk\AbhishekThakur\NodeJS\CallbackNodeJSApplication>
Learn the Concept of Callback in Node.JS

Comparison between Blocking and Non-Blocking Calls

With the help of above two examples, we can compare the blocking and the non-blocking calls in the following way.

The first example demonstrated that the program will be blocked until it finishes reading the file and after that it will proceed to end the program. The second example demonstrated that the program will not wait to finish the reading operation on the file but it will proceed to print “Program has successfully ended” on the console and simultaneously, the program will continue to read the file without blocking.

Source Code for Concept of Callback in Node.JS

Conclusion:

In this article, we have covered the callback concept in Node.js which is required by a beginner developer to work. Under this callback concept, we have demonstrated two examples, one for the blocking call and other for the non-blocking call. After the comparison of both the concepts, it can be concluded that a blocking program executes in a sequential manner whereas a non-blocking program does not execute sequentially. Thus, blocking program may be useful from the programming point of view because it is easier to implement the business logic with the help of blocking calls. Non-blocking calls program can be made to execute sequentially where it needs to keep the processing data within the same block. However, with the non-blocking calls the Node.js is capable of processing multiple instructions simultaneously without blocking or waiting for file I/O read.

Learn the Concept of Callback in Node.JS was last modified: January 6th, 2017 by Sabeer Shaikh

本文前端(javascript)相关术语:javascript是什么意思 javascript下载 javascript权威指南 javascript基础教程 javascript 正则表达式 javascript设计模式 javascript高级程序设计 精通javascript javascript教程

主题: Node.js
分页:12
转载请注明
本文标题:Learn the Concept of Callback in Node.JS
本站链接:http://www.codesec.net/view/521477.html
分享请点击:


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 前端(javascript) | 评论(0) | 阅读(30)