控制台上出现意外的JavaScript输出
我试图运行一段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/');
回答如下:
fs.readFile()是一个异步方法,所以它可能会或者可能不会在你的代码的其余部分之前完成,它只是在它完成时才完成。
看看readFileSync()
https://nodejs/api/fs.html#fs_fs_readfilesync_path_options
控制台上出现意外的JavaScript输出
我试图运行一段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/');
回答如下:
fs.readFile()是一个异步方法,所以它可能会或者可能不会在你的代码的其余部分之前完成,它只是在它完成时才完成。
看看readFileSync()
https://nodejs/api/fs.html#fs_fs_readfilesync_path_options
与本文相关的文章
评论列表 (0)
- 暂无评论