簡體   English   中英

控制台上的JavaScript輸出異常

[英]Unexpected JavaScript output on console

我試圖運行一段Node.js代碼。 這是代碼:

 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()是一個異步方法,因此它可能會或可能不會在其余代碼之前完成,只是在完成后才完成。

簽出readFileSync()

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM