How can I create a Readable that pipes to a Writable and that will allow me to add content to it from time to time?

107 Views Asked by At

What I want to do is probably easy, but after working on this for awhile the implementation that I came up with is a little complicated.

This is what I want to do: I want to be able to create a Readable and pipe it to a Writable and be able to add additional data to the Readable from time to time (asynchronously) and have it continue to pipe the data to the Writable, and then at some later time shut it off.

The following solution probably works (I haven't tested it much), but it seems too complicated to be the right way to do this.

What is the right and easy way of doing this?

const fs = require('fs');
const {
    Readable
} = require('stream');
const writable = fs.createWriteStream('./foo.log', {
    flags: 'w'
});
const asyncIterable = {
    concat: function(char) {
        setImmediate(() => {
            this.resolve({
                value: char,
                done: false
            });
        });
    },
    close: function() {
        setImmediate(() => {
            this.resolve({
                done: true
            });
        });
    },
    [Symbol.asyncIterator]: function() {
        return {
            next: () => {
                return new Promise((r, j) => {
                    this.resolve = r;
                });
            }
        }
    }
};

let readable = Readable.from(asyncIterable);

readable.pipe(writable);

let i = setInterval(() => {
    asyncIterable.concat(':-)');
}, 1000)

setTimeout(() => {
    clearInterval(i);
    asyncIterable.close();
}, 10000)
0

There are 0 best solutions below