Browse Source

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>
v7.x
Linus Unnebäck 9 years ago
committed by James M Snell
parent
commit
4a87abb8e8
  1. 7
      doc/api/fs.md
  2. 5
      lib/fs.js
  3. 12
      test/parallel/test-fs-read-stream.js

7
doc/api/fs.md

@ -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

5
lib/fs.js

@ -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);
}

12
test/parallel/test-fs-read-stream.js

@ -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);

Loading…
Cancel
Save