stream流

stream

stream的类型有四种,常见的是前面两种

image

三段逐渐升级的返回读取文件的代码

  1. fs读取写入
const fs = require("fs");
const server = require("http").createServer();

server.on("request", (req, res) => {
  // solution1
  fs.readFile("text-file.txt", (err, data) => {
    if (err) {
      console.log(err);
    }
    res.end(data);
  });
});

server.listen(8000, "127.0.0.1", () => {
  console.log("Listrning......");
});

  1. 可读流
const fs = require("fs");
const server = require("http").createServer();

server.on("request", (req, res) => {
  // solution 2: streams
  const readable = fs.createReadStream("text-file.txt");
  readable.on("data", (chunk) => {
    res.write(chunk);
  });
  readable.on("end", () => {
    res.end();
  });
  readable.on("error", (err) => {
    console.log(err);
    res.statusCode = 500;
    res.end("File not found!");
  });

});

server.listen(8000, "127.0.0.1", () => {
  console.log("Listrning......");
});

  1. 管道传输
const fs = require("fs");
const server = require("http").createServer();

server.on("request", (req, res) => {
  // solution 3 : pipe
  const readable = fs.createReadStream("text-file.txt");
  // 格式:从一个源可以读流到目的流
  // readableSource.pipe(writeableDest)
  readable.pipe(res);
});

server.listen(8000, "127.0.0.1", () => {
  console.log("Listrning......");
});

posted @ 2022-06-18 02:52  kihyun  阅读(24)  评论(0编辑  收藏  举报