gpt4 book ai didi

javascript - 为什么我不能在 fs.readFile 中使用 response.write?

转载 作者:行者123 更新时间:2023-11-30 10:31:11 24 4
gpt4 key购买 nike

这是我的代码。

var server = http.createServer(function(request, response){
console.log('Connection');
var path = url.parse(request.url).pathname;
path = path.substr(1);

switch(path){
case '':
response.writeHead(200, {'Content-Type':'text/html'});
response.end();
break;
case 'socket.html':
response.write("read file"); //works
fs.readFile(__dirname + '\\' + path, function(error, data){
if (error){
response.writeHead(404); //this doesn't work
}
else{
response.writeHead(200, {'Content-Type':'text/html'}); //doesn't work
response.write("OK"); //doesn't work
}
});
response.end();
break;
default:
response.writeHead(404);
response.end();
break;
}
});

服务器监听端口 8001,当我访问 http://myhost.com:8001/socket.html 时,我只能看到“读取文件”。响应方法似乎在回调函数 readFile 中损坏了。有人可以告诉我为什么并给我一个解决方案吗?谢谢!(请原谅我糟糕的英语 :))。

最佳答案

您过早结束响应。您传递给 readFile 的函数是一个异步回调,它在整个 switch 语句之后运行。

关于javascript - 为什么我不能在 fs.readFile 中使用 response.write?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16909054/

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