const http = require("http");
const { createReadStream } = require("fs");
const stream = createReadStream("./big.txt", "utf-8");
const server = http.createServer((req, res) => {
console.log("hehehe");
// const stream = createReadStream("./big.txt", "utf-8");
stream.on("open", () => {
console.log("hohoho");
stream.pipe(res);
});
});
server.listen(5000);
(代码结果)
hehehe
如果
const stream = createReadStream("./big.txt", "utf-8");
是外部回调服务器连接不正常如果我把
const stream = createReadStream("./big.txt", "utf-8");
在回调,然后一切工作。似乎
stream.pipe(res)
做了res.end()
做的事情。但我不明白pipe(res)
是怎么做到的。
我刚刚也遇到了这个问题,我的猜测是因为在创建服务器之前已经打开了用于读取流的文件。因此,stream.on("open")
的回调函数将永远不会被调用。