[英]How do I return a file-stream from buffer?
我已經在 mysql 數據庫上存儲了我的圖像,它的大小(以字節為單位)和它的類型。
當我獲取它時,我正在取回圖像的緩沖區,現在我試圖弄清楚如何將它發送回我的客戶端以便它呈現圖像?
我的路線內的代碼:
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] }
Fastify 在reply.send()
方法中也支持 stream 和緩沖。
在這里如何管理它們:
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 ,因為它似乎不再需要維護 - 問題未解決 - 並且 node.js 中的默認stream
模塊已得到很大改進)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.