繁体   English   中英

全局范围 createReadStream 不适用于回调

[英]global scope createReadStream doesn't work for callback

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
  1. if const stream = createReadStream("./big.txt", "utf-8"); 在回调之外,则服务器连接无法正常工作。

  2. 如果我把const stream = createReadStream("./big.txt", "utf-8"); 内部回调然后一切正常。

  3. 似乎stream.pipe(res)做了res.end()的工作。 但我不明白pipe(res)如何完成这项工作。

好吧,我也遇到了这个问题,我的猜测是因为在创建服务器之前已经打开了读取流的文件。 所以stream.on("open")的回调函数永远不会被调用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM