Skip to content

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

Notifications You must be signed in to change notification settings

raph-of-burgondy/readable-buffer

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 

Repository files navigation

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.

About

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

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published