What is a callback in Node.js?
Hey readers, in this article, we will be covering all about the callback concept in Node js and its works along with examples. Before jumping directly to the working part, we will learn about Node.js and the basics of what exactly a callback is in Node js. So if you are new to all these concepts, don’t worry, we will be covering it right from the fundamentals and will then move to differences. So keep reading.
Introduction
It is an open-source organization and it provides a runtime environment for running JavaScript code beyond your browser. It is not a framework neither it is a programming language. It is mostly used in the backend for building API services, accessing databases, etc.
The Node js runtime is based on Chrome’s V8 JavaScript engine. Node js is a lightweight and scalable network-driven app framework built on an asynchronous event-driven JavaScript runtime. The development of Node js applications can be readily scaled in both horizontal and vertical orientations. Both client-side and server-side apps are built with Node js. It has an open-source JavaScript runtime environment/model that allows single modules to be cached. As a result, Node.js popularity JS is predicted to skyrocket in 2022.
Why do developers use Node js for building applications?
Following are the reasons for choosing Node js over other backend languages:
- Easy to learn as it uses JavaScript
- Used for agile development and prototyping
- Provides fast and scalable services
- Asynchronous nature
- Uses “Single-threaded-event-loop” architecture
Node js helps developers build large complex applications with ease by using microservices. It can handle thousands of requests coming to the server without slowing down the system. Using microservices in Node js, one can easily scale a large-scale system and can divide it into different chunks for feature updates. It helps add independent features to the application without changing other services.
Uses cases/Applications
Both tech stacks are being widely used for developing web apps. Large tech giants like Netflix, Airbnb, and Instagram use this tech stack in their applications.
Node.js common use cases
It is largely used by developers in the backend of an application. Due to its non-blocking I/O and asynchronous nature, it has become the primary language used on the server side. Tech giants like Netflix, PayPal, Linkedin, and Uber use it for building API and servers.
Following are the uses case of Node js due to which it is widely used for building complex back-end applications and server-side work related to data, API, and database:
- API server
- Data streaming
- Microservices
- Building Real-time applications
Callback in Node js
A callback function is a function that is called when a task is completed, which helps to avoid any blocking and allows other code to run in the meantime. A callback is an asynchronous counterpart of a function that is invoked when a task is completed. Because of the Callback idea, Node.js can handle a huge number of requests without having to wait for a function to produce a result, making it very scalable. Consider the following scenario: When a function in Node.js begins reading a file, it instantly returns control to the execution environment so that the next instruction can be executed. To avoid blocking or waiting for File I/O, the callback function will be invoked after the file I/O is completed.
Example
Example 1: Node js code for synchronously reading a file (blocking code). Create a text file called example1.txt and fill it with the following information:
Hello Developers!!! Learn NodeJS with Codedamn
Node js
// JavaScript code
let fs = require("fs");
let filedata = fs.readFileSync('example1.txt');
console.log(filedata.toString());
console.log("End of Program execution");
Code language: JavaScript (javascript)
Explanation: The fs library is used to perform file-system operations. readFileSync()
is a synchronous function that freezes execution until it completes. The function stops the program until it reads the file, and only then does it terminate it.
Example 2: Node.js code for asynchronously reading a file (non-blocking function). Make a text file called example2.txt with the contents listed below.
Hello Developers!!! Learn NodeJS with Codedamn
Node js
Create a file called async.js with the following code:
//JavaScript code
let fs = require("fs");
fs.readFile('example2.txt', function (ferr, filedata) {
if (ferr) return console.error(ferr); console.log(filedata.toString());
});
console.log("End of Program execution");
Code language: JavaScript (javascript)
Explanation: The fs library is used to perform file-system operations. Because the readFile()
the function is asynchronous, the control returns to the next instruction in the program instantly while the function continues to operate in the background. A callback function is supplied, which is called when the background tasks are completed.
Conclusion
This was all about callback in Node js. If you have any queries or you think we missed something, do drop a text in the comment section. If you want to learn Node js, check out Codedamn courses and the developer section if you like reading articles. Do join our community at Codedamn! Hope you like it.
Sharing is caring
Did you like what mansi wrote? Thank them for their work by sharing it on social media.
No comments so far
Curious about this topic? Continue your journey with these coding courses: