创建自己的流

创建一个Writable Stream

const {Writable} = require("stream")

const outStream = new Writable({
    write(chunk, encoding, callback) {
        console.log(chunk.toString())
        callback()
    }
})
// process.stdin用户输入的的stream
process.stdin.pipe(outStream)
// 上面等价于下面
// process.stdin.on('data', (chunk)=> {
//     outStream.write(chunk)
// })
  • 保存文件为 writable.js 然后用node 运行
  • 不管你输入什么,都会得到相同的结果

创建一个Writable Stream

const {Readable} = require("stream");

const inStream = new Readable();
inStream.push("ABCDEFGHIJKLM");
inStream.push("NOPQRSTUVWXYZ");

inStream.push(null); // No more data 没有数据了
// 在数据写好后读数据
inStream.on('data', (chunk) => {
    process.stdout.write(chunk)
    console.log('写数据了')
})
// 等同上面
// inStream.pipe(process.stdout);
  • 保存文件为 writable.js 然后用node 运行
  • 不管你输入什么,都会得到相同的结果

改进

const {Readable} = require("stream");

const inStream = new Readable({
    read(size) {
        const char = String.fromCharCode(this.currentCharCode++)
        this.push(char);
        console.log(`推了 ${char}`)
        if (this.currentCharCode > 90) { // Z
            this.push(null);
        }
    }
})

inStream.currentCharCode = 65 // A
// 别人调用read读数据才推数据
// process.stdout标准输出事件
inStream.pipe(process.stdout)
  • 保存文件为 readable2.js然后用 node 运行
  • 这次的数据是按需供给的,对方调用read我们才会给一次数据

Duplex Stream

const {Duplex} = require("stream");
const inoutStream = new Duplex({
    write(chunk, encoding, callback) {
        console.log(chunk.toString());
        callback();
    },

    read(size) {
        this.push(String.fromCharCode(this.currentCharCode++));
        if (this.currentCharCode > 90) {
            this.push(null);
        }
    }
})
inoutStream.currentCharCode = 65;
process.stdin.pipe(inoutStream).pipe(process.stdout);

Transform Stream

const { Transform } = require("stream");

const upperCaseTr = new Transform({
    transform(chunk, encoding, callback) {
        this.push(chunk.toString().toUpperCase());
        callback();
    }
});

// process.stdin输入事件的数据调用upperCaseTr方法把小写转化为大写,再通过process.stdout输出
process.stdin.pipe(upperCaseTr).pipe(process.stdout);
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 2018web前端最新面试题总结 一、Html/Css基础模块 基础部分 什么是HTML?答:​ HTML并不是...
    duans_阅读 10,089评论 3 27
  • 曾经学C++的STL中的IOStream,输入输出流,看个代码 眼角湿润了,这是大学的记忆啊,大学时我们幸苦的学习...
    转角遇见一直熊阅读 4,751评论 3 5
  • 面试题一:https://github.com/jimuyouyou/node-interview-questio...
    R_X阅读 5,613评论 0 5
  • --如果你想成为一个Node高手,那么流一定是武功秘籍中不可缺少的一个部分 详细讲解stream以及一些实例 ht...
    lmem阅读 4,432评论 0 1
  • https://nodejs.org/api/documentation.html 工具模块 Assert 测试 ...
    KeKeMars阅读 11,555评论 0 6

友情链接更多精彩内容