我試圖運行一段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文件的內容)
爲什麼要在那裏第一次,考慮'fs.readFile'是一個異步方法,不是順序是否正確? – Teemu