I'm trying to write an uploaded file in nodejs 18.12. from a ReadableStream with pipeTo to a file on the harddrive. But the following fails
const fs = require('fs');
var path = __dirname + '/test.png';
const writeStream = fs.createWriteStream(path);
// stream is a ReadableStream object
stream.pipeTo(writeStream).on('finish', async () => {
console.log('DONE');
})
with
TypeError: ReadableStream.prototype.pipeTo's first argument must be a WritableStream
But I have not found any docs how to work correcty with pipeTo and to store the data into a file. Searching for WritableStream didn't help me either. I'm using graphql-yoga 3.x and the ReadableStream is what I'm getting from the framework.
I also tried a solution from here to convert the stream into a Readable
const { Readable } = require('node:stream');
var readStream = new Readable().wrap(stream);
which failed with stream.on is not a function
I also tried a solution from here with Readable.fromWeb
const writeStream = fs.createWriteStream(path);
var readStream = Readable.fromWeb(stream);
readStream.pipe(writeStream).on('finish', async () => {
console.log('DONE');
})
which got me this strange error:
TypeError: The "readableStream" argument must be an instance of ReadableStream.
Received an instance of ReadableStream
I also now found an example on graphql-yoga website for v2, but it wont work neither.
The pipe flow looks like this:
ReadableStream -pipeTo-> TransformStream -pipeTo-> WriteableStream
But you have to create a clean WritableStream, this is like a buffer to Write something to somewhere.
A readableStream is a Stream that read bytes from some object, in your case read a photo from File is a readable Stream, like that:
this code convert a file into a readstream, after that you have to create a WriteStream for another reason, for example (in my case is the response), but you can write another file for example to pipe to this, like this: