2017-12-27 157 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