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
3 changes: 2 additions & 1 deletion doc/api/fs.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -838,7 +838,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);
});