如何为 createReadStream 分配缓冲区

How to assign a buffer to createReadStream

根据 official documentcreateReadStream 可以接受缓冲区类型作为 path 参数。

但是很多问答只提供如何通过string发送参数的解决方案,而不是buffer

如何正确设置 buffer 参数以满足 createReadStreampath

这是我的代码:

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

```

使用内置 stream 库中的 PassThrough 方法:

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