Node.js Callback Function - Tutorial Kart
[Pages:6]Node.js Callback Function
Node.js Callback Function
Node.js Callback Function : Asynchronism is one of the fundamental factor for Node.js to have become popular. And Callback is the realization of asynchronism for functions. Generally, in Node.js, most of the functions that work on resources have callback variants.
When an asynchronous function is called upon a resource for some task, the control is let immediately to continue with the subsequent statements after the function. The task on the resource would start in parallel. This helps Node.js continue with other tasks while the function is working with the resource. Once the task with the resource is completed, Node.js resumes with the callback function. Callback function is called with arguments : data object, result object and (or) error object containing information regarding the task.
Blocking Function : In contrast to asynchronous function, a synchronous function blocks the execution until the task on the resource is completed. Therefore synchronous function is also called as blocking function.
Node.js Nested Callback Function: If there are multiple operations to be done on the resource sequentially, and also has to be done asynchronously, you may nest the callback functions, one in another.
Now we shall see the working of a callback function in comparison with a blocking function, on reading (task) a file (resource).
Example for Node.js Blocking Function Example for Node.js Callback Function Example for Node.js Nested Callback Function
Example for Blocking Function
Following is an example node script which reads a sample.txt file synchronously.
read- file- sync .js
var fs = require('fs'); // read file sample.txt var data = fvsa.rrefasdF=ilereSqyunirce(('s'fasm');ple .txt'); c onsole.log("Reading f/il/erceoamd pflieletesdam:p"le+.txt new Dvaatred()a.ttaoI=SOfsS.treriandgF()il)e;Sync ('sample.t xt '); ccoonnssoolele..lologg((""ARfetaedring file completed : " + new Date().toISOString()); readFileSync statement : " + new Dcaotnes(o)l.et.oloISgO("SAtfrtienrg(r)e)a;dFileSync statement : " + new Date().toISOString());
When the above program is run
Terminal Output
arjun@arjunVPCEH26EN:~/nodejs$ node read-file-sync.js Reading file completed :a2rj0u1n7@-a1r0j-un-VPCEH26EN:~/nodejs$ node read-file-sync.js 19T12:21:40.103Z ARfetaedrirnegadfiFleilecSoymnpcleted : 2017-10-19T12:21:40.103Z sAtfatteermreenatdF:il2e0S1y7n-c1s0t-atement : 2017-10-19T12:21:40.105Z 19T12:21:40.105Z
TheAfter readFileSync statement is always executed only after reading the file is completed.fs.readFileSync is blocking the execution flow.
Example for Node.js Callback Function
Following is an example node script which reads a sample.txt file asynchronously, with the help of Node.js Callback Function.
read- file- async .js
var fs = require('fs');
// read file sample.txt fs.readFile('sample.txt', v//arcfasllb=acrekqfuuirnec(t'fiosn'); that is called when reading file is done /f/unrecatidonf(ileerrs,admaptlae).t{xt
if (err) throw err; fs/./redaadtaFilies(a'sabmufpfler.txt', cocno/tn/asicnoailnellg.bloafgicle(k"Rcfeuoanndcteitninogtn that is called when reading file is done file fcuonmcptiloente(edrr:, "d+ata) { new Date().ifto(IeSrrO)Stthrrinogw()e)r;r; }); // data is a buffer containing file content consolec.olongs(o"lAe.fltoegr("Reading file completed : " + new Date().toISOString()); r}e)a;dFile asynchronously : " + new Date().toISOString()); console.log("After readFile asynchronously : " + new Date().toISOString());
When the above program is run
Terminal Output
arjun@arjunVPCEH26EN:~/nodejs$ node read-file-async.js After readFile aasryjunnc@hraornjuonu-sVlyPC: EH26EN:~/nodejs$ node read-file-async.js 2017-101A9fTte1r2:re2a5d:3F6ile.9a8s2yZnchronously : 2017-10-19T12:25:36.982Z RReeaaddiningg ffiliele ccoommppleletteedd : 2017-10-19T12:25:36.987Z : 2017-1019T12:25:36.987Z
You may observe that even after executing console.log("After readFile asynchronously statement, it took around 5ms to complete reading the file. fs.readFile('sample.txt', callback function{..}) has not blocked the execution, instead a new process is started in parallel with the main control flow, to read the file (perform the task on resource).
Example for Node.js Nested Callback Function
To demonstrate Node.js Nested Callback Function, we shall consider a scenario of renaming a file and then deleting it using asynchronous functions.
nodejs- nest ed- c allbac k.js
var fs = require('fs');
fs.rename('sample.txt', 'sample_old.txt', v//ar1fsst =carlel qbuaicrek('fs'); func t ion function (err) { fsif.r(eenrar)mteh(r'osawmeprlre;.txt', 'sample_old.txt',
c onsole.log('File Ren/a/m1esdt.'c);all back function
fs.ufnulinnckt(i'osnam(eprler)_o{ld.tx
t', if (err) throw err; // 2nd call back
functiocnonsole.log('File Renamed.');
funcftsio.unn(lienrkr()'s{ample_old.txt', if (err) throw err;
console//.lo2gn(d'Fcileall back function
Deleted.')f;unction (err) { }
);
if (err) throw err;
}
);
console.log('File Deleted.');
}
);
}
);
When the above Node.js example is run with node
Terminal Output
arjun@arjunVPCEH26EN:~/nodejs$ node nodejs-nestedc allbac k.js FailrejuRne@naarmjuend-.VPCEH26EN:~/nodejs$ node nodejs-nested-callback.js File Deleted. File Renamed. File Deleted.
Conclusion :
In this Node.js Tutorial ? Node.js Callback Function, we have learnt the execution flow of Callback functions and how they are non-blocking, and also how to use nested callback functions with examples.
Node.js
Node.js Tutorial
Get Started W ith Node.js
Install Node.js Ubuntu Linux
Install Node.js Windows Node.js - Basic Example Node.js - Command Line Arguments Node.js - Modules Node.js - Create a module Node.js - Add new functions to Module Node.js - Override functions of Module Node.js - Callback Function Node.js - forEach
E xp re s s .j s
Express.js Tutorial What is Express.js? Express.js Application Example Install Express.js Express.js Routes Express.js Middleware Express.js Router
Node.js Buffers
Node.js Buffer - Create, Write, Read Node.js Buffer - Length Node.js - Convert JSON to Buffer Node.js - Array to Buffer
Node.js HTTP
Node.js - Create HTTP Web Server Node.js - Redirect URL
Node.js MySQL
Node.js MySQL Node.js MySQL - Connect to MySQL Database Node.js MySQL - SELECT FROM Node.js MySQL - SELECT WHERE Node.js MySQL - ORDER BY Node.js MySQL - INSERT INTO Node.js MySQL - UPDATE
Node.js MySQL - DELETE Node.js MySQL - Result Object
Node.js MongoDB
Node.js MongoDB Node.js - Connect to MongoDB Node.js - Create Database in MongoDB Node.js - Drop Database in MongoDB Node.js - Create Collection in MongoDB Node.js - Delete Collection in MongoDB Node.js - Insert Documents to MongoDB Collection MongoError: failed to connect to server
Node.js Mongoose
Node.js Mongoose Tutorial Node.js Mongoose - Installation Node.js Mongoose - Connect to MongoDB Node.js Mongoose - Define a Model Node.js Mongoose - Insert Single Document to MongoDB Node.js Mongoose - Insert Multiple Documents to MongoDB
Node.js URL
Node.js - Parse URL parameters
Node.js FS (File System)
Node FS Node FS - Read a File Node FS - Create a File Node FS - Write to a File Node FS - Append to a File Node FS - Rename a File Node FS - Delete a File Node FS Extra - Copy a Folder
Node.js JSON
Node.js Parse JSON Node.js Write JSON Object to File
Node.js Error Handling
Node.js Try Catch
Node.js Examples
Node.js Examples Node.js - Handle Get Requests Node.js Example - Upload files to Node.js server
Useful Resources
Node.js Interview Questions How to Learn Programming
................
................
In order to avoid copyright disputes, this page is only a partial summary.
To fulfill the demand for quickly locating and searching documents.
It is intelligent file search solution for home and business.
Related download
- meshcentral2
- i n s t al l i n g u s i n g t h e g i t h u b s ou rc e c od e c l on e
- ubuntu guide
- install instructions for ubuntu windows macos sunos
- how to code in nodejs digitalocean
- ubuntu 20 04 driver release notes nvidia
- install node js using terminal in ubuntu
- codeready single node openshift ubuntu os
- callback function tutorial kart
- ubuntu linux 20 04 lts installation lenovo