其他分享
首页 > 其他分享> > stream流

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......");
});

标签:fs,const,stream,res,require,readable,server
来源: https://www.cnblogs.com/kihyunBlog/p/16387550.html