I need to read a file in node but, for example, if the size of the file is 4KB I need to read the first 1K and print it on the console, then, the second Kb of the file... and continue to the end. The problems is that I don't know how to "stop" reading after the first Kb and continue afterwards by there.
Any help?
Thanks¡¡
You can use fs.read
to read a fixed number of bytes and async
to loop.
untested code:
var buf = new Buffer();
var length=4096; // you can get this with fs.stat
var position=0;
fs.open('/tmp/file', 'r', function(err, fd) {
if(err) throw err;
async.whilst(
function() { position < length; },
function(callback) {
fs.read(fd, buf, null, 1024, position, function(err, bytesRead, buf) {
if(err) callback(err);
if(bytesRead!=1024) throw new Error('bytes read not 1024');
console.log(buf.toString());
position+=bytesRead;
callback();
});
},
function(err) {
if(err) throw err;
}
);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.