简体   繁体   中英

Unexpected JavaScript output on console

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.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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM