2017-12-27 159 views
0

我試圖運行一段Node.js代碼。這是代碼:控制檯上出現意外的JavaScript輸出

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/');

當我跑在我的筆記本電腦上的Linux終端上,該input.txt的文件的內容出現在最後一行的「服務器運行」命令後, 。理想情況下,首先readfile命令輸出應該在那裏,不是嗎?

輸出出來如下:

計劃結束

服務器在運行....

(txt文件的內容)

+1

爲什麼要在那裏第一次,考慮'fs.readFile'是一個異步方法,不是順序是否正確? – Teemu

回答

5

FS。 readFile()是一種異步方法,因此它可能會或可能不會在其他代碼完成之前完成,只是在完成時才完成。

退房readFileSync()

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

+0

雖然此鏈接可能有助於您對問題的回答,但您可以通過將鏈接的重要部分放入您的答案中來改善此答案,這可確保您的答案在鏈接被更改或刪除時仍然是答案:) – WhatsThePoint