Call backs in node js: ---------------------- - we have two type of communications. 1. Synchronous Communication. 2. Asynchronous Communication - We Can Implement the Asynchronous Communication with the help of callbacks. - Synchronous Communication Called as Blocked Communication. - Asynchronous Communication Called as Non Blocked Communication. Ex. we want to read the data from two text files. 1. file1.txt 2. file2.txt [Note : if "file1.txt" reading operation fails , then node engine won't reads file2.txt called as Synchronous Communication] [Note : if "file1.txt" reading operation fails , then node engine will reads file2.txt called as Asynchronous Communication] - "fs" is the file system, (predefined) module used to read the data from the static files. - readFileSync( - ) is the predefined method in "fs" module used to read the data synchronously. - readFile( - ) is the predefined method in "fs" module used to read the data asynchronously. - "__dirname" is the global property used to read the real path of application. ------------------ 26-10-2017 sample.json ------------------ syncExample.js -------------- var fs = require("fs"); var http = require("http"); var server = http.createServer(my_fun); function my_fun(req,res){ var result = fs.readFileSync(__dirname+"/sample.json"); res.send(result.toString()); } server.listen(8080); console.log("Server Listening the Port No.8080"); asyncExample.js --------------- var http = require("http"); var fs = require("fs"); var server = http.createServer(my_fun); function my_fun(req,res){ res.writeHead(200,{'Content-Type':'text/plain'}); fs.readFile(__dirname+"/sample.json", function(err,data){ res.write(data.toString()); res.end(); }); }; server.listen(8080); console.log("Server Listening the Port No.8080");
Node.js Tutorial for Beginners-3 Call Backs In Node JS: - YouTube | |
2 Likes | 2 Dislikes |
50 views views | 118,767 followers |
Entertainment | Upload TimePublished on 19 Apr 2018 |
Không có nhận xét nào:
Đăng nhận xét