0

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)

1
  • 1
    Why should it be there first, considering fs.readFile is an asynchronous method, isn't the order correct? Commented Dec 27, 2017 at 12:55

1 Answer 1

5

fs.readFile() is an async method, so it may or may not finish before the rest of your code, it's just done when it's done.

check out readFileSync()

https://nodejs.org/api/fs.html#fs_fs_readfilesync_path_options

Sign up to request clarification or add additional context in comments.

1 Comment

While this link may assist in your answer to the question, you can improve this answer by taking vital parts of the link and putting it into your answer, this makes sure your answer is still an answer if the link gets changed or removed :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.