简体   繁体   English

控制台上的JavaScript输出异常

[英]Unexpected JavaScript output on console

I was trying to run a piece of Node.js code. 我试图运行一段Node.js代码。 This is the code: 这是代码:

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

When I ran it on the Linux terminal on my laptop, the content of the input.txt file appeared after the "Server running" command in the last line. 当我在笔记本电脑的Linux终端上运行它时,input.txt文件的内容出现在最后一行的“服务器正在运行”命令之后。 Ideally, first the readfile command output should have been there, shouldn't it? 理想情况下,首先应该将readfile命令输出到那里,不是吗?

The output coming out is as follows: 输出结果如下:

Program ended 程序结束

Server running at.... 服务器正在运行。

(content of the txt file) (txt文件的内容)

fs.readFile() is an async method, so it may or may not finish before the rest of your code, it's just done when it's done. fs.readFile()是一个异步方法,因此它可能会或可能不会在其余代码之前完成,只是在完成后才完成。

check out readFileSync() 签出readFileSync()

https://nodejs.org/api/fs.html#fs_fs_readfilesync_path_options 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