From 80711b0ff90cede610365cba65e46c3128b57bfd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Felix=20Geisendo=CC=88rfer?= Date: Thu, 14 Apr 2011 22:45:32 +0200 Subject: [PATCH] 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 --- doc/api/fs.markdown | 5 +++++ lib/fs.js | 5 +++++ test/simple/test-file-write-stream.js | 2 ++ 3 files changed, 12 insertions(+) diff --git a/doc/api/fs.markdown b/doc/api/fs.markdown index a092aa2b3c9..574171fa5a0 100644 --- a/doc/api/fs.markdown +++ b/doc/api/fs.markdown @@ -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. +### file.bytesWritten + +The number of bytes written so far. Does not include data that is still queued +for writing. + ### fs.createWriteStream(path, [options]) Returns a new WriteStream object (See `Writable Stream`). diff --git a/lib/fs.js b/lib/fs.js index 89dc2142b3e..f73327bc997 100644 --- a/lib/fs.js +++ b/lib/fs.js @@ -1019,6 +1019,7 @@ var WriteStream = fs.WriteStream = function(path, options) { this.flags = 'w'; this.encoding = 'binary'; this.mode = parseInt('0666', 8); + this.bytesWritten = 0; options = options || {}; @@ -1070,6 +1071,10 @@ WriteStream.prototype.flush = function() { return; } + if (method == fs.write) { + self.bytesWritten += arguments[1]; + } + // stop flushing after close if (method === fs.close) { if (cb) { diff --git a/test/simple/test-file-write-stream.js b/test/simple/test-file-write-stream.js index 0fb5b45a6b6..b5eb1e45731 100644 --- a/test/simple/test-file-write-stream.js +++ b/test/simple/test-file-write-stream.js @@ -58,6 +58,8 @@ file } }) .addListener('close', function() { + assert.strictEqual(file.bytesWritten, EXPECTED.length * 2); + callbacks.close++; assert.throws(function() { file.write('should not work anymore');