I am new to nodejs and callbacks.
So I have this code where I read a file when a request to server is initiated via HTTP:
var http = require("http");
var fs = require("fs");
http.createServer(function(request,response){
response.writeHead(200,{'Content-Type':'text/plain'});
response.end("Server runnning...");
fs.readFile('new.txt',function(err,data){
if(err){
console.error(err);
return;
}
console.log(data.toString());
});
}).listen(1234);
When I run the code, the contents of the file are displayed/logged twice on console.
lorem ipsum
lorem ipsum
The file contents are:
lorem ipsum
readFile() Method. Parameters: The method accept three parameters as mentioned above and described below: filename: It holds the name of the file to read or the entire path if stored at other location. encoding: It holds the encoding of file.
readFile. Returns the contents of the file named filename. If encoding is specified then this function returns a string. Otherwise it returns a buffer.
callback : A function with two parameters: error and data .
readFileSync() is synchronous and blocks execution until finished. These return their results as return values. readFile() are asynchronous and return immediately while they function in the background.
When you type a URL into the browser's address bar it will typically make two requests:
/favicon.ico
Two requests means two calls to fs.readFile
since you call that for every request.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With