Node JS Callback

Saurabh Kumar
Jul 20, 2017 · 3 min read

Node JS handle all asynchronous calls via callback. Hey wait, what is callback..?? well, callbacks in the general definition are just functions that you pass to other functions. It is called at the completion of certain task.

doesn’t make any sense..!! function passing to another function…!! what’s going on here..?? let me give a simple example of callback

fs module is built-in module of Node JS which is used to work with file system of your computer .Here i’m using fs.stat() function to get file information of input.txt which give information about file size, created date, last modified date, bla bla.. bla bla…

Let’s analyse how this code snippet is working. Here we can see that fs.stat()function is taking two arguments. First argument is the path of the file and second argument is a function, which is nothing but a callback function.

Let’s get into more details of code. First fs.stat()will try to find whether the file exists or not, then it will try to get all information about that file. If it successfully get all information then that data is passed into statparameter of callback function. If some error happen in the process, that error is passed into errparameter of callback function. After dealing with the path, callback function get invoked.

Note : According to coding convention of Node JS, the first argument in callback function is for an error object and second argument is for a successful response

If you are making your own custom callback function, it is advisable to follow the same rules.

let’s get our hand dirty with custom callback :)

Here we define a function with two parameters 1. arg: any argument you pass 2. Callback : a callback function, and assign that function to a constant variable checkFileType.

Now we are calling the function from line 10 with the help of checkFileType which takes two parameters 1. 15 which is a number and 2. A callback function

That’s a simple example of custom callback.Now take few minutes to analyse what we have done till now.

Try to pass a string as parameter in the place of 15 and see the output. I hope i am able to give you some better understanding of callback… 😄


About the author

I work on multiple technologies and deep learning with a vision to make this world a little beautiful..! 😊

feel free to follow me on GitHub 👉

or connect with me on LinkedIn 👉

for more post by me check out 👇

)
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade