I have stored my image, it's size in bytes and its type on a mysql db.
When I fetch it I am getting back a buffer for the image and now Im trying to figure out how to send it back to my client so that it renders the image?
Code inside of my route:
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);
Whats the next step?
If I would to log myReadableStreamBuffer
I just get:
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] }
createReadStream() allows you to open up a readable stream in a very simple manner. All you have to do is pass the path of the file to start streaming in. It turns out that the response (as well as the request) objects are streams. So we will use this fact to create a http server that streams the files to the client.
No, fopen() does not return a buffer, it returns a FILE pointer. FILE is an opaque structure.
To create a transform stream, we need to import the Transform class from the Node. js stream module. The transform stream constructor accepts a function containing the data processing/transformation logic: const fs = require("fs"); const { Transform } = require("stream"); const fileStream= fs.
Fastify support stream and buffer too in the reply.send()
method.
Here how to manage them:
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)
(I would avoid stream-buffers
package since it seems no more maintained - issues unanswered - and the default stream
module in node.js has been greatly improved)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With