Feature: WriteStream#bytesWritten property

Implemented a new property for writable file streams that keeps track
of the bytes written (not queued). This helps when you are piping
another stream to a file, and would like to know how big the file is
without having to issue another stat call.

closes #930
This commit is contained in:
Felix Geisendörfer 2011-04-14 22:45:32 +02:00 committed by Ryan Dahl
parent e2d9018535
commit 80711b0ff9
3 changed files with 12 additions and 0 deletions

View File

@ -396,6 +396,11 @@ An example to read the last 10 bytes of a file which is 100 bytes long:
`fd` is the file descriptor used by the WriteStream. `fd` is the file descriptor used by the WriteStream.
### file.bytesWritten
The number of bytes written so far. Does not include data that is still queued
for writing.
### fs.createWriteStream(path, [options]) ### fs.createWriteStream(path, [options])
Returns a new WriteStream object (See `Writable Stream`). Returns a new WriteStream object (See `Writable Stream`).

View File

@ -1019,6 +1019,7 @@ var WriteStream = fs.WriteStream = function(path, options) {
this.flags = 'w'; this.flags = 'w';
this.encoding = 'binary'; this.encoding = 'binary';
this.mode = parseInt('0666', 8); this.mode = parseInt('0666', 8);
this.bytesWritten = 0;
options = options || {}; options = options || {};
@ -1070,6 +1071,10 @@ WriteStream.prototype.flush = function() {
return; return;
} }
if (method == fs.write) {
self.bytesWritten += arguments[1];
}
// stop flushing after close // stop flushing after close
if (method === fs.close) { if (method === fs.close) {
if (cb) { if (cb) {

View File

@ -58,6 +58,8 @@ file
} }
}) })
.addListener('close', function() { .addListener('close', function() {
assert.strictEqual(file.bytesWritten, EXPECTED.length * 2);
callbacks.close++; callbacks.close++;
assert.throws(function() { assert.throws(function() {
file.write('should not work anymore'); file.write('should not work anymore');