From ce4ac15850d3f8596de1ac78701e899f21019165 Mon Sep 17 00:00:00 2001 From: Daniil Demidovich Date: Tue, 22 Sep 2020 13:44:58 +0300 Subject: [PATCH] lib: fix readFile flag option typo MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR-URL: https://github.com/nodejs/node/pull/35292 Reviewed-By: Andrey Pechkurov Reviewed-By: Ruben Bridgewater Reviewed-By: Masashi Hirano Reviewed-By: Matteo Collina Reviewed-By: Benjamin Gruenbaum Reviewed-By: Zeyu Yang Reviewed-By: Gerhard Stöbich --- lib/fs.js | 2 +- test/parallel/test-fs-readfile-flags.js | 51 +++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 1 deletion(-) create mode 100644 test/parallel/test-fs-readfile-flags.js diff --git a/lib/fs.js b/lib/fs.js index c570a8c9f4fc2e..8e26339e215c89 100644 --- a/lib/fs.js +++ b/lib/fs.js @@ -322,7 +322,7 @@ function readFile(path, options, callback) { return; } - const flagsNumber = stringToFlags(options.flags); + const flagsNumber = stringToFlags(options.flag); path = getValidatedPath(path); const req = new FSReqCallback(); diff --git a/test/parallel/test-fs-readfile-flags.js b/test/parallel/test-fs-readfile-flags.js new file mode 100644 index 00000000000000..2aceee25506419 --- /dev/null +++ b/test/parallel/test-fs-readfile-flags.js @@ -0,0 +1,51 @@ +'use strict'; + +// Test of fs.readFile with different flags. +const common = require('../common'); +const fs = require('fs'); +const assert = require('assert'); +const path = require('path'); +const tmpdir = require('../common/tmpdir'); + +tmpdir.refresh(); + +{ + const emptyFile = path.join(tmpdir.path, 'empty.txt'); + fs.closeSync(fs.openSync(emptyFile, 'w')); + + fs.readFile( + emptyFile, + // With `a+` the file is created if it does not exist + { encoding: 'utf8', flag: 'a+' }, + common.mustCall((err, data) => { assert.strictEqual(data, ''); }) + ); + + fs.readFile( + emptyFile, + // Like `a+` but fails if the path exists. + { encoding: 'utf8', flag: 'ax+' }, + common.mustCall((err, data) => { assert.strictEqual(err.code, 'EEXIST'); }) + ); +} + +{ + const willBeCreated = path.join(tmpdir.path, 'will-be-created'); + + fs.readFile( + willBeCreated, + // With `a+` the file is created if it does not exist + { encoding: 'utf8', flag: 'a+' }, + common.mustCall((err, data) => { assert.strictEqual(data, ''); }) + ); +} + +{ + const willNotBeCreated = path.join(tmpdir.path, 'will-not-be-created'); + + fs.readFile( + willNotBeCreated, + // Default flag is `r`. An exception occurs if the file does not exist. + { encoding: 'utf8' }, + common.mustCall((err, data) => { assert.strictEqual(err.code, 'ENOENT'); }) + ); +}