Skip to content

Commit

Permalink
fs: set encoding on fs.createWriteStream
Browse files Browse the repository at this point in the history
Enable encoding option on fs.createWriteStream.

PR-URL: #1844
Reviewed-By: Colin Ihrig <[email protected]>
  • Loading branch information
yosuke-furukawa committed Jun 2, 2015
1 parent a4dbf45 commit 8357c50
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 1 deletion.
3 changes: 2 additions & 1 deletion doc/api/fs.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -847,7 +847,8 @@ Returns a new WriteStream object (See `Writable Stream`).
`options` may also include a `start` option to allow writing data at
some position past the beginning of the file. Modifying a file rather
than replacing it may require a `flags` mode of `r+` rather than the
default mode `w`.
default mode `w`. The `encoding` can be `'utf8'`, `'ascii'`, `binary`,
or `'base64'`.

Like `ReadStream` above, if `fd` is specified, `WriteStream` will ignore the
`path` argument and will use the specified file descriptor. This means that no
Expand Down
3 changes: 3 additions & 0 deletions lib/fs.js
Original file line number Diff line number Diff line change
Expand Up @@ -1807,6 +1807,9 @@ function WriteStream(path, options) {
this.pos = this.start;
}

if (options.encoding)
this.setDefaultEncoding(options.encoding);

if (typeof this.fd !== 'number')
this.open();

Expand Down
32 changes: 32 additions & 0 deletions test/parallel/test-fs-write-stream-encoding.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
'use strict';
const common = require('../common');
const assert = require('assert');
const fs = require('fs');
const path = require('path');
const stream = require('stream');
const firstEncoding = 'base64';
const secondEncoding = 'binary';

const examplePath = path.join(common.fixturesDir, 'x.txt');
const dummyPath = path.join(common.tmpDir, 'x.txt');

const exampleReadStream = fs.createReadStream(examplePath, {
encoding: firstEncoding
});

const dummyWriteStream = fs.createWriteStream(dummyPath, {
encoding: firstEncoding
});

exampleReadStream.pipe(dummyWriteStream).on('finish', function() {
const assertWriteStream = new stream.Writable({
write: function(chunk, enc, next) {
const expected = new Buffer('xyz\n');
assert(chunk.equals(expected));
}
});
assertWriteStream.setDefaultEncoding(secondEncoding);
fs.createReadStream(dummyPath, {
encoding: secondEncoding
}).pipe(assertWriteStream);
});

0 comments on commit 8357c50

Please sign in to comment.