繁体   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