I want to read a file with an interval of 64 bytes. And I also do not want to use any functionality that interanlly implements buffering. I wanted to do the buffering manually. So I started using fs.read (). I tried, but I really don’t know how to set the position , which says where to read in the file and offset in the buffer to start writing.
So I found some resources and started to implement it myself. But what I did seems completely 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;
var length = 511;
var position = 0;
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)
})
}
}
, . .
- ?
, ?