我仍然不清楚資料如何在管道中的流之間流動。大多數示例都使用檔案或內置生成器作為起點,然后在另一個檔案或輸出中完成。但他們中的大多數都沒有展示如何制作我們自己的管道。
所以,我需要生成從外部機器接收到的另一個資料的資料,然后將其轉換成某種東西,并通過 UDP 套接字重新傳輸資料(stream-udp請不要包)。我知道如何獲取資料,也知道如何通過資料報發送資料,但我對如何將它們作為接收和發送的資料進行流式傳輸感到困惑。
比方說。我有這樣的事情:
import { pipeline, Readable, Transform, Writable } from "stream";
const reader = new Readable();
const transform = new Transform();
const writable = new Writable();
// How to flow the data from reader to transform to writer?
transform.on('data', (chunk) => {
console.log('Transforming ' chunk);
const newchunk = chunk 'transformed ';
// how to send the data from here to writable?
transform.push(newchunk);
})
writable.on('???', (chunk) => {
// write the chunk into something
console.log(chunk);
}
pipeline(
reader,
transform,
writable,
(err) => {
console.log('Done')
if (err) console.error(err);
}
)
reader.push('this is new data');
那么,有人可以幫助我了解讀者發送文本到轉換,然后轉換,然后以可寫方式接收的事情是如何流動的嗎?
一個簡單的例子就足夠了,喜歡reader.push('this is data')并以writer.on('???', (chunk) => console.log(chunk))
謝謝你。
uj5u.com熱心網友回復:
流 Api 的問題之一是有很多為什么要實作并且示例不一致
這是一個簡單的例子:
CharStream - 是一個可讀流:從 z 生成一個字符流,然后當它到達 z 時發送 null 并完成
Uppercasify - Transformer 接收每個字母并將其更改為大寫
StringWritable - 將所有字母聚合為一個字串,并在完成控制臺記錄它
import { Transform, Readable, Writable } from 'readable-stream'
class CharStream extends Readable {
constructor(options = {}) {
super(options)
this.charCode = 97;
}
_read() {
this.push(`${String.fromCharCode(this.charCode )}\n`);
if (this.charCode > 'z'.charCodeAt(0)) this.push(null);
};
}
class Uppercasify extends Transform {
constructor(options = {}) {
super(options)
this.counter = 0
}
_transform(chunk, encoding, done) {
done(null, chunk.toString().toUpperCase())
}
}
class StringWritable extends Writable {
constructor(options = {}) {
super(options)
this.currentString = "";
}
_write(chunk, encoding, done) {
this.currentString = chunk.toString().replace("\n", "")
done()
}
}
const cs = new CharStream()
const uts = new Uppercasify()
const out = new StringWritable()
const stream = cs.pipe(uts).pipe(out)
stream.on('finish', () => console.log(out.currentString))
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/526402.html
上一篇:如何在連接AWSEC2服務器和AWSS3存盤檔案(InvalidAccessKeyId)時修復此AWS錯誤?
下一篇:帶有“useBreadcrumbsfromuse-react-router-breadcrumbs”的唯一鍵道具問題
