Skip to content

Commit 8357c50

Browse files
fs: set encoding on fs.createWriteStream
Enable encoding option on fs.createWriteStream. PR-URL: #1844 Reviewed-By: Colin Ihrig <[email protected]>
1 parent a4dbf45 commit 8357c50

File tree

3 files changed

+37
-1
lines changed

3 files changed

+37
-1
lines changed

doc/api/fs.markdown

+2-1
Original file line numberDiff line numberDiff line change
@@ -847,7 +847,8 @@ Returns a new WriteStream object (See `Writable Stream`).
847847
`options` may also include a `start` option to allow writing data at
848848
some position past the beginning of the file. Modifying a file rather
849849
than replacing it may require a `flags` mode of `r+` rather than the
850-
default mode `w`.
850+
default mode `w`. The `encoding` can be `'utf8'`, `'ascii'`, `binary`,
851+
or `'base64'`.
851852

852853
Like `ReadStream` above, if `fd` is specified, `WriteStream` will ignore the
853854
`path` argument and will use the specified file descriptor. This means that no

lib/fs.js

+3
Original file line numberDiff line numberDiff line change
@@ -1807,6 +1807,9 @@ function WriteStream(path, options) {
18071807
this.pos = this.start;
18081808
}
18091809

1810+
if (options.encoding)
1811+
this.setDefaultEncoding(options.encoding);
1812+
18101813
if (typeof this.fd !== 'number')
18111814
this.open();
18121815

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
'use strict';
2+
const common = require('../common');
3+
const assert = require('assert');
4+
const fs = require('fs');
5+
const path = require('path');
6+
const stream = require('stream');
7+
const firstEncoding = 'base64';
8+
const secondEncoding = 'binary';
9+
10+
const examplePath = path.join(common.fixturesDir, 'x.txt');
11+
const dummyPath = path.join(common.tmpDir, 'x.txt');
12+
13+
const exampleReadStream = fs.createReadStream(examplePath, {
14+
encoding: firstEncoding
15+
});
16+
17+
const dummyWriteStream = fs.createWriteStream(dummyPath, {
18+
encoding: firstEncoding
19+
});
20+
21+
exampleReadStream.pipe(dummyWriteStream).on('finish', function() {
22+
const assertWriteStream = new stream.Writable({
23+
write: function(chunk, enc, next) {
24+
const expected = new Buffer('xyz\n');
25+
assert(chunk.equals(expected));
26+
}
27+
});
28+
assertWriteStream.setDefaultEncoding(secondEncoding);
29+
fs.createReadStream(dummyPath, {
30+
encoding: secondEncoding
31+
}).pipe(assertWriteStream);
32+
});

0 commit comments

Comments
 (0)