Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a temporary write stream?

I have a file stream that I want to pass in a method named transformRead(), this one accepts a readStream and a writeStream, but I don't know how to create the temporary write stream... do I have to use a file ? I just want a kind of pipe() from rs to ws, then ws is gzipped and sent to response.

            // Get file stream
            var rs = store.getReadStream(fileId);
            var ws = ?????; 

            // Execute transformation
            store.transformRead(rs, ws, fileId);

            var accept = req.headers['accept-encoding'] || '';

            // Compress data if supported by the client
            if (accept.match(/\bdeflate\b/)) {
                res.writeHead(200, {
                    'Content-Encoding': 'deflate',
                    'Content-Type': file.type
                });
                ws.pipe(zlib.createDeflate()).pipe(res);

            } else if (accept.match(/\bgzip\b/)) {
                res.writeHead(200, {
                    'Content-Encoding': 'gzip',
                    'Content-Type': file.type
                });
                ws.pipe(zlib.createGzip()).pipe(res);

            } else {
                res.writeHead(200, {});
                ws.pipe(res);
            }
like image 462
Karl.S Avatar asked Aug 01 '15 07:08

Karl.S


People also ask

How do you pipe a writable stream?

The pipe event in a Writable Stream is emitted when the stream. pipe() method is being called on a readable stream by attaching this writable to its set of destinations. Return Value: If the pipe() method is being called then this event is emitted else it is not emitted.

How do you use fs write stream?

createWriteStream() creates a writable stream in a very simple manner. After a call to fs. createWriteStream() with the filepath, you have a writeable stream to work with. It turns out that the response (as well as the request) objects are streams.

What is a writable stream?

A writable stream is an abstraction for a destination to which data can be written. An example of that is the fs. createWriteStream method. A duplex streams is both Readable and Writable. An example of that is a TCP socket.


2 Answers

Finally, someone told me about using stream.PassThrough();

So the simplest and "native" solution is :

var ws = new stream.PassThrough();
like image 73
Karl.S Avatar answered Sep 21 '22 00:09

Karl.S


Use through2 to easily create transform (read/write) stream

like image 27
krl Avatar answered Sep 20 '22 00:09

krl