Skip to content

Commit 460a501

Browse files
committed
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
1 parent e3e3588 commit 460a501

File tree

3 files changed

+23
-1
lines changed

3 files changed

+23
-1
lines changed

doc/api/fs.md

+7
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,13 @@ added: v0.1.93
181181
Emitted when the `ReadStream`'s underlying file descriptor has been closed
182182
using the `fs.close()` method.
183183

184+
### readStream.bytesRead
185+
<!-- YAML
186+
added: REPLACEME
187+
-->
188+
189+
The number of bytes read so far.
190+
184191
### readStream.path
185192
<!-- YAML
186193
added: v0.1.93

lib/fs.js

+4-1
Original file line numberDiff line numberDiff line change
@@ -1679,6 +1679,7 @@ function ReadStream(path, options) {
16791679
this.end = options.end;
16801680
this.autoClose = options.autoClose === undefined ? true : options.autoClose;
16811681
this.pos = undefined;
1682+
this.bytesRead = 0;
16821683

16831684
if (this.start !== undefined) {
16841685
if (typeof this.start !== 'number') {
@@ -1774,8 +1775,10 @@ ReadStream.prototype._read = function(n) {
17741775
self.emit('error', er);
17751776
} else {
17761777
var b = null;
1777-
if (bytesRead > 0)
1778+
if (bytesRead > 0) {
1779+
self.bytesRead += bytesRead;
17781780
b = thisPool.slice(start, start + bytesRead);
1781+
}
17791782

17801783
self.push(b);
17811784
}

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

+12
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,18 @@ var rangeFile = path.join(common.fixturesDir, 'x.txt');
1010
var callbacks = { open: 0, end: 0, close: 0 };
1111

1212
var paused = false;
13+
var bytesRead = 0;
1314

1415
var file = fs.ReadStream(fn);
16+
var fileSize = fs.statSync(fn).size;
17+
18+
assert.strictEqual(file.bytesRead, 0);
1519

1620
file.on('open', function(fd) {
1721
file.length = 0;
1822
callbacks.open++;
1923
assert.equal('number', typeof fd);
24+
assert.strictEqual(file.bytesRead, 0);
2025
assert.ok(file.readable);
2126

2227
// GH-535
@@ -31,6 +36,9 @@ file.on('data', function(data) {
3136
assert.ok(!paused);
3237
file.length += data.length;
3338

39+
bytesRead += data.length;
40+
assert.strictEqual(file.bytesRead, bytesRead);
41+
3442
paused = true;
3543
file.pause();
3644

@@ -42,11 +50,15 @@ file.on('data', function(data) {
4250

4351

4452
file.on('end', function(chunk) {
53+
assert.strictEqual(bytesRead, fileSize);
54+
assert.strictEqual(file.bytesRead, fileSize);
4555
callbacks.end++;
4656
});
4757

4858

4959
file.on('close', function() {
60+
assert.strictEqual(bytesRead, fileSize);
61+
assert.strictEqual(file.bytesRead, fileSize);
5062
callbacks.close++;
5163

5264
//assert.equal(fs.readFileSync(fn), fileContent);

0 commit comments

Comments
 (0)