Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

lib: fix readFile flag option #35292

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion lib/fs.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
51 changes: 51 additions & 0 deletions test/parallel/test-fs-readfile-flags.js
Original file line number Diff line number Diff line change
@@ -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');
O4epegb marked this conversation as resolved.
Show resolved Hide resolved
fs.closeSync(fs.openSync(emptyFile, 'w'));

fs.readFile(
emptyFile,
// With `a+` the file is created if it does not exist
O4epegb marked this conversation as resolved.
Show resolved Hide resolved
{ 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
O4epegb marked this conversation as resolved.
Show resolved Hide resolved
{ 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'); })
);
}