作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
根据 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/
我是一名优秀的程序员,十分优秀!