I was trying to run a piece of Node.js code. This is the code:
var fs = require("fs");
fs.readFile('input.txt', function(err, data) {
if (err) return console.error(err);
console.log(data.toString());
});
console.log("Program Ended");
var http = require("http");
http.createServer(function(request, response) {
// Send the HTTP header
// HTTP Status: 200 : OK
// Content Type: text/plain
response.writeHead(200, {
'Content-Type': 'text/plain'
});
// Send the response body as "Hello World"
response.end('Hello World\n');
}).listen(8081);
// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');
When I ran it on the Linux terminal on my laptop, the content of the input.txt file appeared after the "Server running" command in the last line. Ideally, first the readfile command output should have been there, shouldn't it?
The output coming out is as follows:
Program ended
Server running at....
(content of the txt file)
fs.readFileis an asynchronous method, isn't the order correct?