Tony Tony - 2 months ago 52
Node.js Question

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)
});
});
}
});


```

Answer

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
});