NodeJs Tutorials
- NodeJs
- Install NodeJs
- Why use NodeJs
- NodeJs Process Model
- create First Application
- Run NodeJs Application
- Node.js Console
- Node.Js Modules
- URL Modules
- node.js Callback
- Node.js Events
- Upload Files
- Upload single & Multiple Files
- NodeJs File System
- NodeJs Email
- Debugging NodeJs
- .ENV
- NodeJs Mysql
- Helpers
- encription and decription in nodeJs
- Query string
- Date & Time
- Express Js
- Template Engine with Express
- MVC Pattern in Node.Js
- list of NPM Module
- Middleware
- Body Parser
- Render
- Nodemon module
- Morgan module
- Flash Message in ExpressJs
- Session
- Session store in database
- Cookies
- Helmet
- Multer
- Router: How To Use Routing In Node.Js
- App.Js
- express.json() and express.urlencoded()
- REST APIs in NodeJs
- Gloabal Objects
- Submit Form Data
- How to get Post Data in Node.js
- How to Get URL Parameters in Node.js
- How to create Node Project
- How to Insert Form Data Into the MySql Table Using Node.js
- How to fetch Data from MySQL database table using Node.js
- CRUD Example
- Await and Async
- Promises
- Login Example
- Password Encription
- How to validate Form (Form Validation) in Node.Js?
- Registration & Login form usingn Node.Js & MySql?
- Forgot & Reset Password
- File Upload in Node.Js with ExpressJs
- Resize Image Before Upload using Multer Sharp
- Upload multiple file using node.js with multer module
- Upload file using node.js with multer module
- Client IP Address
- REST API Downloading File in NodeJs
- Export and Download CSV From MySQL Database
- CRUD REST API
- CRUD REST API Example 2
- Enable HTTPS using Node
- How to send EMAIL using NodeJs?
- Dynamic dependent dropdown using NodeJs?
- Autocomplete Search
- Get and Send Data From Ajax Request
- Get and Post Data using Ajax
- Passport Authentication
- Node Js Data type
- Node Js Error
- Node Js Array Function
- Node Js String Function
- Puppeter Module
What is Node.Js Callback?
What is Callbacks:
In Node.js, callbacks are generally used.
Callback is an asynchronous equivalent for a function. It is called at the completion of each task.
A callback is a function which is called when a task is completed. a callback function allows other code to run in the meantime.
Callback is called when task get completed. 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 start reading 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.
All APIs of Node are written in a way to supports callbacks
Example
File Name : myfile.txt
Hello Developer!!!
Learn NodeJS with ItTutorial.
Blocking Code Example
File Name : test.js
var fs = require("fs");
var filedata = fs.readFileSync('myfile.txt');
console.log(filedata.toString());
console.log("End of Program execution");
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 :-
Learn NodeJS with ItTutorial.
End of Program execution
Example 2 :- Non Blocking Code
Code for reading a file asynchronously (non-blocking code) in Node.js. Create a text file myfile.txt with the following content.
File Name : test.js
var fs = require("fs");
fs.readFile('myfile.txt', function (ferr, filedata) {
if (ferr) return console.error(ferr);
console.log(filedata.toString());
});
console.log("End of Program execution");
fs library is loaded to handle file-system related operations. The readFile() function is asynchronous and control return immediately to the next instruction in the program while the function keep running in the background. A callback function is passed which gets called when the task running in the background are finished.
Output :-
Hello Developer!!!
Learn NodeJS with ItTutorial.
Note :-
You can see that above two examples explain the concept of blocking and non-blocking calls. The first example shows that program blocks until it reads the file and then only it proceeds to end the program on the other hand in second example, program does not wait for file reading but it just proceeded to print "End of Program execution" and same time program without blocking continues reading the file.
So we can say that, a blocking program executes very much in sequence. It is also easier to implement the logic from programming point of view in block programs. But non-blocking programs does not execute in sequence, so in case a program needs to use any data to be processed
Difference between Events and Callbacks:
Events and Callbacks look similar but the differences lies in the fact that callback functions are called when an asynchronous function returns its result where as event handling works
on the observer pattern. Whenever an event gets fired,
its listener function starts executing. Node.js has multiple in-built events available through events module and EventEmitter class which is used to bind events and event listeners.
How Node Applications Work?
In Node Application, any async function accepts a callback as the last parameter and a callback function accepts an error as the first parameter. Create a text file named myfile.txt
create nodejs file test.js
var fs = require("fs");
fs.readFile('myfile.txt', function (err, data) {
if (err) {
console.log(err.stack);
return;
}
console.log(data.toString());
});
console.log("Program Execution Ended");
Here fs.readFile() is a async function whose purpose is to read a file. If an error occurs during the read operation, then the err object will contain the corresponding error, else data will contain the contents of the file. readFile passes err and data to the callback function after the read operation is complete, which finally prints the content.
Program Execution Ended
Hello Developer!!!
Learn NodeJS with ItTutorial.
Callbacks
A callback is a function passed as an argument into another function, which can then be invoked (called back) inside the outer function to complete some kind of action at a convenient time. The invocation may be immediate (sync callback) or it might happen at a later time (async callback).
// Sync callback
function say(callback) {
callback();
}
say(() => { console.log('Hello'); });
more_Work(); // will run after console.log
// Async callback
const fs = require('fs');
fs.readFile('/file.md', function callback(err, data) {
// fs.readFile is an async method provided by Node
if (err) throw err;
console.log(data);
});
more_Work(); // will run before console.log
An async callback may be called when an event happens or when a task completes. It prevents blocking by allowing other code to be executed in the meantime.