gpt4 book ai didi

javascript - 如何为 createReadStream 分配缓冲区

转载 作者:搜寻专家 更新时间:2023-10-30 21:07:08 25 4
gpt4 key购买 nike

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

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

如何正确设置buffer参数以满足createReadStream路径

这是我的代码:

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

关于javascript - 如何为 createReadStream 分配缓冲区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38953360/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com