NodeJs for beginners: 04 – Callbacks in Nodejs

A callback is a function which called after a task is completed which helps in preventing any kind of blocking and a callback function allows other code to run in the meantime. Callback is called when task is completed and is asynchronous equivalent for a function. Using Callback concept, Node.js can process a large number of requests without waiting for any function to return the result which makes Node.js highly scalable. For example: In Node.js, when a function starts reading a file, it returns the control to execution environment immediately so that the next instruction can be executed. Once file I/O gets completed, callback function will get called to avoid blocking or wait for File I/O.

Example of Nodejs Without Callaback: Create a text file fs.txt with the following content:

Code for reading a file synchronously (blocking code) in Node.js:

fs library is loaded to handle file-system related operations. The readFileSync function is synchronous and blocks execution until finished. The function blocks the program until it reads the file and then only it proceeds to end the program.

Output of the above code:

If you see the output, then the contents of the fs.txt file were printed first and then program ended. This means that you code was blocked by fs module and after it is completed then only next operation was performed. Using callback you can avoid this blocking of code. let’s see how we can do that in next example.

Example of Nodejs With Callaback: Code for reading a file asynchronously (non-blocking code) in Node.js:

Inside readFile function we have given filePath and after that we are passing a callback function which will excecute after file has been read. While nodejs is reading the file, the execution will not stop there instead it will move directly to next line i.e. console.log.

Output of the above code:

As you can see above code, message Program ended! has been printed first and then the content of file is printed. Thats the benefit of the callbacks in node js. You dont have to wait until a task is completed. Using callbacks increases the performance of nodejs server.

When to use callbacks?

Callbacks can be used in many places but there are some places where you must use callbacks like API calls, Operations with database and if you think a task will take some time to executes and you dont want node js to stop or wait until that task is done then you should always use Callbacks.

What can we use instead of Callbacks

ES-6 async & await can be used instead of callbacks.

NOTE* If you are getting SyntaxError: Cannot use import statement outside a module when running code in the terminal then add the following line in the package.json file: