gpt4 book ai didi

node.js - 为什么浏览器没有输出?

转载 作者:太空宇宙 更新时间:2023-11-03 23:39:09 24 4
gpt4 key购买 nike

这是我的代码:

var http = require('http')

http.createServer(function (req, res) {
res.writeHead(200, {
"Content-Type": "json"
});
fs.readdir('.', function (error, files) {
if (error)
res.end(util.format(error))

files.forEach(function (file) {
fs.stat(file, function (erro, stats) {
console.log(JSON.stringify(stats))
res.write(JSON.stringify(stats))
})
})
})
}).listen(3000);
console.log("server is running!")

当我访问http://127.0.0.1:3000/时,没有任何输出,但控制台输出是:

{"dev":0,"mode":16822,"nlink":1,"uid":0,"gid":0,"rdev":0,"ino":0,"size":0,"atime":"2014-11-20T13:36:19.000Z","mtime":"2014-11-20T13:36:19.000Z","ctime":"2014-11-20T13:31:53.000Z"}

{"dev":0,"mode":33206,"nlink":1,"uid":0,"gid":0,"rdev":0,"ino":0,"size":11,"atime":"2014-11-20T13:56:21.000Z","mtime":"2014-11-20T13:56:21.000Z","ctime":"2014-11-20T13:56:21.000Z"}

{"dev":0,"mode":33206,"nlink":1,"uid":0,"gid":0,"rdev":0,"ino":0,"size":844,"atime":"2014-11-20T14:24:04.000Z","mtime":"2014-11-20T14:24:04.000Z","ctime":"2014-11-20T13:32:19.000Z"}

{"dev":0,"mode":16822,"nlink":1,"uid":0,"gid":0,"rdev":0,"ino":0,"size":0,"atime":"2014-11-20T14:03:56.000Z","mtime":"2014-11-20T14:03:56.000Z","ctime":"2014-11-20T13:56:21.000Z"}

最佳答案

完成 res.write 调用后,您需要调用 res.end()

http.createServer(function (req, res) {
res.writeHead(200, {
"Content-Type": "json"
});
fs.readdir('.', function (error, files) {
if (error)
res.end(util.format(error))

var filesLeft = files.length;
files.forEach(function (file) {
fs.stat(file, function (erro, stats) {
console.log(JSON.stringify(stats))
res.write(JSON.stringify(stats))
// Keep track of how many files' fs.stat calls are left
if (--filesLeft === 0) {
res.end();
}
})
})
})
}).listen(3000);

关于node.js - 为什么浏览器没有输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27052704/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com