如何在可克隆可读的克隆流上使用数据事件? : 节点

How to use data events on cloned streams in cloneable-readable? : NodeJS

我想克隆一个读取流。目前,我正在使用 readable-stream-clone npm 包。使用代码:

const fs = require('fs')
const readStream = fs.createReadStream('smallTextFile.txt', { highWaterMark: 5 })
const ReadableStreamClone = require('readable-stream-clone')

const readStream1 = new ReadableStreamClone(readStream)
const readStream2 = new ReadableStreamClone(readStream)

readStream1.on('data', (chunk) => {
  console.log('1', chunk.toString())
})

readStream2.on('data', (chunk) => {
  console.log('2', chunk.toString())
})

代码的输出是:

1 This 
2 This 
1 is a 
2 is a 
1 small
2 small
1  reco
2  reco
1 rd
2 rd

smallTextFile.txt中的内容:

This is a small record

但使用 readable-stream-clone 的问题是它每周只有 3000 次下载,而且没有授权。 还有一个 npm 包 cloneable-readable it is a licensed package. Can anyone help me implement the above code using the cloneable-readable package?

您可以使用以下代码通过 cloneable-readable 执行相同的操作,它类似于 readable-stream-clone,当您将 steam 包装在 cloneable 中时,它会在输出中为您提供一个新的流。

const fs = require('fs')
const readStream = fs.createReadStream('smallTextFile.txt', { highWaterMark: 5 })
const cloneable = require('cloneable-readable')

const readStream1 = cloneable(readStream);
const readStream2 = cloneable(readStream);

readStream1.on('data', (chunk) => {
  console.log('1', chunk.toString())
})

readStream2.on('data', (chunk) => {
  console.log('2', chunk.toString())
})