From e06ad5faf98a8fb15863ec8a1638ba82bba13427 Mon Sep 17 00:00:00 2001 From: Benjamin Gruenbaum Date: Mon, 12 Mar 2018 12:02:20 +0200 Subject: [PATCH] fs: use encoding in readFile MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Use the encoding parameter passed to fsPromises.readFile if it is passed. Currently the encoding parameter is ignored in fsPromises. PR-URL: https://github.com/nodejs/node/pull/19296 Fixes: https://github.com/nodejs/node/issues/19286 Reviewed-By: Sakthipriyan Vairamani Reviewed-By: Evan Lucas Reviewed-By: Anna Henningsen Reviewed-By: Colin Ihrig Reviewed-By: Gus Caplan Reviewed-By: James M Snell Reviewed-By: Michaƫl Zasso Reviewed-By: Joyee Cheung Reviewed-By: Yuta Hiroto --- lib/fs/promises.js | 7 ++++++- test/parallel/test-fs-promises-writefile.js | 8 ++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/lib/fs/promises.js b/lib/fs/promises.js index a36d845d5177fa..8884777e5e16de 100644 --- a/lib/fs/promises.js +++ b/lib/fs/promises.js @@ -157,7 +157,12 @@ async function readFileHandle(filehandle, options) { chunks.push(buffer.slice(0, totalRead)); } while (totalRead === chunkSize); - return Buffer.concat(chunks); + const result = Buffer.concat(chunks); + if (options.encoding) { + return result.toString(options.encoding); + } else { + return result; + } } // All of the functions are defined as async in order to ensure that errors diff --git a/test/parallel/test-fs-promises-writefile.js b/test/parallel/test-fs-promises-writefile.js index e2ae289b180bc2..280bce864229ce 100644 --- a/test/parallel/test-fs-promises-writefile.js +++ b/test/parallel/test-fs-promises-writefile.js @@ -35,7 +35,15 @@ async function doRead() { assert.deepStrictEqual(buf, data); } +async function doReadWithEncoding() { + const data = await fsPromises.readFile(dest, 'utf-8'); + const syncData = fs.readFileSync(dest, 'utf-8'); + assert.strictEqual(typeof data, 'string'); + assert.deepStrictEqual(data, syncData); +} + doWrite() .then(doAppend) .then(doRead) + .then(doReadWithEncoding) .then(common.mustCall());