fs: add bytesRead to ReadStream

Add a property named bytesRead that exposes how many bytes that have
currently been read from the file. This brings consistency with
WriteStream that has bytesWritten and net.Socket which have both
bytesRead and bytesWritten.

Fixes: https://github.com/nodejs/node/issues/#7938
PR-URL: https://github.com/nodejs/node/pull/7942
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Anna Henningsen <anna@addaleax.net>
Reviewed-By: Ben Noordhuis <info@bnoordhuis.nl>
This commit is contained in:
Linus Unnebäck 2016-08-01 21:31:16 +02:00 committed by James M Snell
parent f59b8888f1
commit 4a87abb8e8
3 changed files with 23 additions and 1 deletions

View File

@ -181,6 +181,13 @@ added: v0.1.93
Emitted when the `ReadStream`'s underlying file descriptor has been closed
using the `fs.close()` method.
### readStream.bytesRead
<!-- YAML
added: REPLACEME
-->
The number of bytes read so far.
### readStream.path
<!-- YAML
added: v0.1.93

View File

@ -1679,6 +1679,7 @@ function ReadStream(path, options) {
this.end = options.end;
this.autoClose = options.autoClose === undefined ? true : options.autoClose;
this.pos = undefined;
this.bytesRead = 0;
if (this.start !== undefined) {
if (typeof this.start !== 'number') {
@ -1774,8 +1775,10 @@ ReadStream.prototype._read = function(n) {
self.emit('error', er);
} else {
var b = null;
if (bytesRead > 0)
if (bytesRead > 0) {
self.bytesRead += bytesRead;
b = thisPool.slice(start, start + bytesRead);
}
self.push(b);
}

View File

@ -10,13 +10,18 @@ var rangeFile = path.join(common.fixturesDir, 'x.txt');
var callbacks = { open: 0, end: 0, close: 0 };
var paused = false;
var bytesRead = 0;
var file = fs.ReadStream(fn);
var fileSize = fs.statSync(fn).size;
assert.strictEqual(file.bytesRead, 0);
file.on('open', function(fd) {
file.length = 0;
callbacks.open++;
assert.equal('number', typeof fd);
assert.strictEqual(file.bytesRead, 0);
assert.ok(file.readable);
// GH-535
@ -31,6 +36,9 @@ file.on('data', function(data) {
assert.ok(!paused);
file.length += data.length;
bytesRead += data.length;
assert.strictEqual(file.bytesRead, bytesRead);
paused = true;
file.pause();
@ -42,11 +50,15 @@ file.on('data', function(data) {
file.on('end', function(chunk) {
assert.strictEqual(bytesRead, fileSize);
assert.strictEqual(file.bytesRead, fileSize);
callbacks.end++;
});
file.on('close', function() {
assert.strictEqual(bytesRead, fileSize);
assert.strictEqual(file.bytesRead, fileSize);
callbacks.close++;
//assert.equal(fs.readFileSync(fn), fileContent);