創(chuàng)建自己的流

創(chuàng)建一個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 運行
  • 不管你輸入什么,都會得到相同的結(jié)果

創(chuàng)建一個Writable Stream

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

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

inStream.push(null); // No more data 沒有數(shù)據(jù)了
// 在數(shù)據(jù)寫好后讀數(shù)據(jù)
inStream.on('data', (chunk) => {
    process.stdout.write(chunk)
    console.log('寫數(shù)據(jù)了')
})
// 等同上面
// inStream.pipe(process.stdout);
  • 保存文件為 writable.js 然后用node 運行
  • 不管你輸入什么,都會得到相同的結(jié)果

改進

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
// 別人調(diào)用read讀數(shù)據(jù)才推數(shù)據(jù)
// process.stdout標(biāo)準(zhǔn)輸出事件
inStream.pipe(process.stdout)
  • 保存文件為 readable2.js然后用 node 運行
  • 這次的數(shù)據(jù)是按需供給的,對方調(diào)用read我們才會給一次數(shù)據(jù)

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輸入事件的數(shù)據(jù)調(diào)用upperCaseTr方法把小寫轉(zhuǎn)化為大寫,再通過process.stdout輸出
process.stdin.pipe(upperCaseTr).pipe(process.stdout);
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 2018web前端最新面試題總結(jié) 一、Html/Css基礎(chǔ)模塊 基礎(chǔ)部分 什么是HTML?答:? HTML并不是...
    duans_閱讀 4,716評論 3 27
  • 曾經(jīng)學(xué)C++的STL中的IOStream,輸入輸出流,看個代碼 眼角濕潤了,這是大學(xué)的記憶啊,大學(xué)時我們幸苦的學(xué)習(xí)...
    轉(zhuǎn)角遇見一直熊閱讀 1,158評論 3 5
  • 面試題一:https://github.com/jimuyouyou/node-interview-questio...
    R_X閱讀 1,761評論 0 5
  • --如果你想成為一個Node高手,那么流一定是武功秘籍中不可缺少的一個部分 詳細(xì)講解stream以及一些實例 ht...
    lmem閱讀 962評論 0 1
  • https://nodejs.org/api/documentation.html 工具模塊 Assert 測試 ...
    KeKeMars閱讀 6,607評論 0 6

友情鏈接更多精彩內(nèi)容