From 8357c5084bf133efa36f727d6f10c3722cb26aa5 Mon Sep 17 00:00:00 2001 From: Yosuke Furukawa Date: Sun, 31 May 2015 02:12:07 +0900 Subject: [PATCH] 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 --- doc/api/fs.markdown | 3 +- lib/fs.js | 3 ++ .../parallel/test-fs-write-stream-encoding.js | 32 +++++++++++++++++++ 3 files changed, 37 insertions(+), 1 deletion(-) create mode 100644 test/parallel/test-fs-write-stream-encoding.js diff --git a/doc/api/fs.markdown b/doc/api/fs.markdown index e16f72cb3bad58..b9eca2f9147b44 100644 --- a/doc/api/fs.markdown +++ b/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 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 diff --git a/lib/fs.js b/lib/fs.js index 4cdd0ef5e31456..35d84da7094a1e 100644 --- a/lib/fs.js +++ b/lib/fs.js @@ -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(); diff --git a/test/parallel/test-fs-write-stream-encoding.js b/test/parallel/test-fs-write-stream-encoding.js new file mode 100644 index 00000000000000..ca02d122e47f08 --- /dev/null +++ b/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); +});