【问题标题】:How to assign a buffer to createReadStream如何将缓冲区分配给 createReadStream
【发布时间】:2016-12-21 13:22:24
【问题描述】:

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

```

【问题讨论】:

    标签: javascript node.js typescript buffer fs


    【解决方案1】:

    使用内置 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
    });
    

    【讨论】:

      猜你喜欢
      • 2021-10-29
      • 2021-03-03
      • 1970-01-01
      • 2017-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多