1.0.2 • Published 6 years ago

readable-buffer v1.0.2

Weekly downloads
3
License
ISC
Repository
github
Last release
6 years ago

readable-buffer

a true streamifying module :)

This very simple but efficient function transforms a Buffer into a Readable Stream

##Description

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"

Usage (simplified example in redis cache usage)

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)
        }
      })

Contributors

....are welcome

License

no licence. use free.