Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign a buffer to createReadStream

According to official document, createReadStream can accept a buffer type as path argument.

But many Q&A only offer solutions of how to send argument by string, not buffer.

How do I set a properly buffer argument to meet path of createReadStream?

This is my code:

fs.access(filePath, (err: NodeJS.ErrnoException) => {
    // Response with 404
    if (Boolean(err)) { res.writeHead(404); res.end('Page not Found!'); return; }

    // Create read stream accord to cache or path
    let hadCached = Boolean(cache[filePath]);
    if (hadCached) console.log(cache[filePath].content)
    let readStream = hadCached
        ? fs.createReadStream(cache[filePath].content, { encoding: 'utf8' })
        : fs.createReadStream(filePath);
    readStream.once('open', () => {
        let headers = { 'Content-type': mimeTypes[path.extname(lookup)] };
        res.writeHead(200, headers);
        readStream.pipe(res);
    }).once('error', (err) => {
        console.log(err);
        res.writeHead(500);
        res.end('Server Error!');
    });

    // Suppose it hadn't cache, there is a `data` listener to store the buffer in cache
    if (!hadCached) {
        fs.stat(filePath, (err, stats) => {
            let bufferOffset = 0;
            cache[filePath] = { content: Buffer.alloc(stats.size, undefined, 'utf8') };  // Deprecated: new Buffer

            readStream.on('data', function(chunk: Buffer) {
                chunk.copy(cache[filePath].content, bufferOffset);
                bufferOffset += chunk.length;
                //console.log(cache[filePath].content)
            });
        });
    }
});

```

like image 925
Tony Avatar asked May 10 '26 15:05

Tony


1 Answers

Use the PassThrough method from the inbuild stream library:

const stream = require("stream");

let readStream = new stream.PassThrough();
readStream.end(new Buffer('Test data.'));

// You now have the stream in readStream
readStream.once("open", () => {
    // etc
});
like image 58
James Marino Avatar answered May 12 '26 04:05

James Marino



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!