javascript - 如何从缓冲区返回文件流?
问题描述
我已经存储了我的图像,它的大小(以字节为单位)及其类型在 mysql db 上。
当我获取它时,我正在取回图像的缓冲区,现在我试图弄清楚如何将它发送回我的客户端以便它呈现图像?
我的路线内的代码:
const img = await db.images.findByPk(parser.setValueAsBIN(p.id));
const myReadableStreamBuffer = new streamBuffers.ReadableStreamBuffer({
frequency: 10, // in milliseconds.
chunkSize: img.Length, // in bytes.
});
myReadableStreamBuffer.put(img.dataValues.imageData);
下一步是什么?
如果我想登录myReadableStreamBuffer
我只是得到:
Readable { _readableState: ReadableState {
objectMode: false,
highWaterMark: 16384,
buffer: BufferList { head: null, tail: null, length: 0 },
length: 0,
pipes: null,
pipesCount: 0,
flowing: null,
ended: false,
endEmitted: false,
reading: false,
sync: true,
needReadable: false,
emittedReadable: false,
readableListening: false,
resumeScheduled: false,
paused: true,
emitClose: true,
autoDestroy: false,
destroyed: false,
defaultEncoding: 'utf8',
awaitDrain: 0,
readingMore: false,
decoder: null,
encoding: null }, readable: true, domain: null, _events: [Object: null prototype] {}, _eventsCount: 0, _maxListeners: undefined, stopped: false, stop: [Function], size: [Function], maxSize: [Function], put: [Function], _read: [Function] }
解决方案
Fastifyreply.send()
方法中也支持流和缓冲区。
在这里如何管理它们:
const fs = require('fs')
const { Readable } = require('stream')
const fastify = require('fastify')({ logger: true })
fastify.get('/', (req, reply) => {
const buffer = fs.readFileSync('demo.png')
reply.type('image/png') // if you don't set the content, the image would be downloaded by browser instead of viewed
reply.send(buffer)
})
fastify.get('/stream', (req, reply) => {
const buffer = fs.readFileSync('demo.png') // sync just for DEMO
const myStream = new Readable({
read () {
this.push(buffer)
this.push(null)
}
})
reply.type('image/png')
reply.send(myStream)
})
fastify.listen(3000)
(我会避免stream-buffers
使用 package,因为它似乎不再需要维护 - 问题未得到解答 - stream
node.js 中的默认模块已得到极大改进)
推荐阅读
- ios - iOS - CIImage autoAdjustmentFilters 泄漏
- javascript - React Native - 打开原生共享
- node.js - 解析来自 mongoose 对象的数组元素的数据产生未定义而简单的元素值正确返回
- php - 查询 PHP 到 Mysql 数据库
- spring-integration - Spring Cloud Stream:如何重新发布到死信队列并抛出异常
- javascript - 随机单词组合javascript
- jquery - 如何获取由 JQuery.data() 创建的具有特定数据属性的元素?
- jenkins - 来自 Jenkins Job 的 Groovy 脚本将数据填充为来自 oracle DB 的组合框需要大量时间
- amazon-web-services - 如何将 S3 存储桶的访问权限限制为特定 VPC,同时允许控制台访问
- java - 未调用 Feign ErrorDecoder