This very simple but efficient function transforms a Buffer into a Readable Stream
function streamify(buf,chunksizemax=16*1024) {
if (!Buffer.isBuffer(buf)) throw Error('!!!! argument must be a buffer')
var size = buf.length
var index = 0
return new Readable({
read(n) {
//buf.slice will limit offset to buf.length
this.push(buf.slice(index,index+n))
index=index+n
if (index >= size) this.push(null)},
highWaterMark : chunksizemax
})
}
buf.slice is memory efficient since "the allocated memory of the two objects (original and sliced buffer) overlap"
I use it especially with ioredis which enable to store buffer
var Redis = require('ioredis');
var redis = new Redis();
const {streamify} = require('readable-buffer')
redis.set(filename, buf)
redis.getBuffer(req.url)
.then((data)=>{
if (data==null) {
//load ressource to cache
} else {
streamify(data).pipe(res)
}
})
....are welcome
no licence. use free.