Saturday 8 April 2017

How to read a file by setting correct offset and position and write to the response in Nodejs with manual buffering?

I want to read a file in 64byte interval. And I also do not want to use any functionality which interanlly implements buffering. I wanted to do buffering manually. So I started using fs.read(). I tried hard but I really don't know how to set position which tells where to read from in the file and offset in the buffer to start writing at.
So I found few resources and started implementing by my own. But what I did seems enterly wrong. Please find my code below.

app.get('/manualBufferAnother', function (req, res, next) {
   var filePath = path.join(__dirname, 'Koala.jpg');
   console.log("FilePath is: "+filePath);
   var fileName = path.basename(filePath);
   var mimeType = mime.lookup(filePath);
   var stat = fs.statSync(filePath);

   res.writeHead(200, {
         "Content-Type": mimeType,
         "Content-Disposition" : "attachment; filename=" + fileName,
         'connection': 'keep-alive',
         "Content-Length": stat.size,
         "Transfer-Encoding": "chunked"
   });

   fs.open(filePath, 'r', function(err, fd) {
       var completeBufferSize = stat.size;
       var offset = 0;  //is the offset in the buffer to start writing at
       var length = 511; //is an integer specifying the number of bytes to read
       var position = 0;  //is an integer specifying where to begin reading 
       from in the file. If position is null, data will be read from the current file position
       var buffer = new Buffer(completeBufferSize);
       buf(res,fd,offset,position,length,buffer,stat);        
   });
 });

var buf = function(res,fd,offset,position,length,buffer,stat) {
if(position+buffer.length < length) {
    fs.read(fd,buffer,offset,length,position,function(error,bytesRead,bufferr {
        res.write(bufferr.slice(0,bytesRead));
        console.log("Bytes Read: "+bytesRead);
        position=position+bufferr.length;
        buf(res,fd,offset,position,length,bufferr,stat);
    })
} else {
    fs.read(fd,buffer,offset,length,position,function(error,bytesRead,bufferr) {
        console.log("Bytes Read in else: "+bytesRead);
        res.end(bufferr.slice(0,bytesRead));
        fs.close(fd)
    })
}
}

I know this code is doing so much wrong thing. But I don't know the right way. Should I use any loop for setting and storing position and offset values? Will be really helpful if you provide me good reference?



via Kishore Kumar Korada

No comments:

Post a Comment