Browse Source

fs: set encoding on fs.createWriteStream

Enable encoding option on fs.createWriteStream.

PR-URL: https://github.com/nodejs/io.js/pull/1844
Reviewed-By: Colin Ihrig <cjihrig@gmail.com>
v2.3.1-release
Yosuke Furukawa 10 years ago
parent
commit
8357c5084b
  1. 3
      doc/api/fs.markdown
  2. 3
      lib/fs.js
  3. 32
      test/parallel/test-fs-write-stream-encoding.js

3
doc/api/fs.markdown

@ -847,7 +847,8 @@ Returns a new WriteStream object (See `Writable Stream`).
`options` may also include a `start` option to allow writing data at `options` may also include a `start` option to allow writing data at
some position past the beginning of the file. Modifying a file rather 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 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 Like `ReadStream` above, if `fd` is specified, `WriteStream` will ignore the
`path` argument and will use the specified file descriptor. This means that no `path` argument and will use the specified file descriptor. This means that no

3
lib/fs.js

@ -1807,6 +1807,9 @@ function WriteStream(path, options) {
this.pos = this.start; this.pos = this.start;
} }
if (options.encoding)
this.setDefaultEncoding(options.encoding);
if (typeof this.fd !== 'number') if (typeof this.fd !== 'number')
this.open(); this.open();

32
test/parallel/test-fs-write-stream-encoding.js

@ -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);
});
Loading…
Cancel
Save