Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 #7938
  • Loading branch information
LinusU committed Aug 5, 2016
commit 460a501d3030e503370f9e3a46d2b4f625668a52
7 changes: 7 additions & 0 deletions doc/api/fs.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 4 additions & 1 deletion lib/fs.js
Original file line number Diff line number Diff line change
Expand Up @@ -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') {
Expand Down Expand Up @@ -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);
}
Expand Down
12 changes: 12 additions & 0 deletions test/parallel/test-fs-read-stream.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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();

Expand All @@ -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);
Expand Down