Search code examples
node.jspipefsnodejs-streamnodejs-server

Node.js: appending to readable stream WHILE it is piped to a writable stream?


My server receives udp packets of audio buffers. I would like to stream these incoming chunks to Google's text-to-speech API.

Using fs streams, is it possible to achieve this in a manner that goes something like this?:

let stream = fs.createReadStream("empty-file-name").pipe(myOutputStreamToAPI);

dgramserver.on('message', (msg, rinfo) => {
        stream.push(msg)
}

In this rough sketch, I would create an empty (possible?) stream, or alternatively create the stream upon the first recieved packet, and the keep pushing to the stream as more packets come in.

Is this possible?

How else can my desired outcome be achieved? Namely, after a readable-stream is piped to a writable-stream, I wish to ADD TO THE READABLE STREAM DYNAMICALLY AND AT DISTINTC TIMES.

This question can also be asked like this: How can I create a readable stream out of dynamically incoming udp packets?

Thank you


Solution

  • Does this give you answer

    const Stream = require('stream')
    
    const readableStream = new Stream.Readable()
    const writableStream = new Stream.Writable()
    
    writableStream._write = (chunk, encoding, next) => {
        console.log(chunk.toString())
        next()
    }
    
    readableStream.pipe(writableStream)
    
    readableStream.push('ping!')
    readableStream.push('pong!')
    
    writableStream.end()