这是我的代码:
const fs = require("fs");
// creat the server
const server = http.createServer((req, res) => {
console.log(req.url, req.method);
res.write("hello out there nice try");
res.end();
fs.readFile('./index.html', (err, data) =>{
if(err){
console.log(err);
res.end();
} else{
res.write(data);
res.end();
}})
});
server.listen(3000, 'localhost', () =>{
console.log("the server is running");
});
每当我运行它的时候,我都会得到这样的错误:
/ GET
events.js:352
throw er; // Unhandled 'error' event
^
Error [ERR_STREAM_WRITE_AFTER_END]: write after end
at writeAfterEnd (_http_outgoing.js:694:15)
at write_ (_http_outgoing.js:706:5)
at ServerResponse.write (_http_outgoing.js:687:15)
at /Users/khadija/Desktop/first-project/app.js:15:17
at FSReqCallback.readFileAfterClose [as oncomplete] (internal/fs/read_file_context.js:73:3)
Emitted 'error' event on ServerResponse instance at:
at writeAfterEndNT (_http_outgoing.js:753:7)
at processTicksAndRejections (internal/process/task_queues.js:83:21) {
code: 'ERR_STREAM_WRITE_AFTER_END'
}
服务器正在运行,但它没有读取index.html文件,这与异步有关吗?
发布于 2021-06-30 07:25:59
在结束响应流之后,您不能写入响应流。
这里:
res.write("hello out there nice try");
res.end();
您似乎想要一个单独的条件分支。其中,如果满足某些条件,则编写“不错的尝试”,否则编写index.html的内容。
因此,您应该这样做:
if (something) {
res.write("hello out there nice try");
res.end();
} else {
fs.readFile('./index.html', (err, data) =>{
if(err){
console.log(err);
res.end();
} else{
res.write(data);
res.end();
}});
}
如果你不那么困惑的话,还有fs.readFileSync
。不过,只要你不过早地结束流,你拥有它的方式应该不会有任何问题。
https://stackoverflow.com/questions/68186688
复制相似问题