Skip to content

Commit 493864a

Browse files
committed
fs: fix confusing flags TypeError msg
File open flags must be an int when passed to the binding layer, but they must be a string when passed to the fs module (numbers are permitted, though undocumented). The module used to do no type checking, so the binding layer error would be thrown, and it was wrong: > fs.openSync('_') TypeError: flags must be an int at TypeError (native) at Object.fs.openSync (fs.js:549:18) It is now: > fs.openSync('_') TypeError: flag must be a string PR-URL: #2902 Reviewed-By: Ben Noordhuis <[email protected]>
1 parent 6cb9e8a commit 493864a

File tree

2 files changed

+18
-3
lines changed

2 files changed

+18
-3
lines changed

lib/fs.js

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -465,10 +465,11 @@ fs.readFileSync = function(path, options) {
465465

466466
// Used by binding.open and friends
467467
function stringToFlags(flag) {
468-
// Only mess with strings
469-
if (typeof flag !== 'string') {
468+
if (typeof flag === 'number')
470469
return flag;
471-
}
470+
471+
if (typeof flag !== 'string')
472+
throw new TypeError('flag must be a string');
472473

473474
switch (flag) {
474475
case 'r' : return O_RDONLY;

test/parallel/test-fs-open-flags.js

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,3 +38,17 @@ assert.equal(fs._stringToFlags('xa+'), O_APPEND | O_CREAT | O_RDWR | O_EXCL);
3838
'x +x x+ rx rx+ wxx wax xwx xxx').split(' ').forEach(function(flags) {
3939
assert.throws(function() { fs._stringToFlags(flags); });
4040
});
41+
42+
// Use of numeric flags is permitted.
43+
assert.equal(fs._stringToFlags(O_RDONLY), O_RDONLY);
44+
45+
// Non-numeric/string flags are a type error.
46+
assert.throws(function() { fs._stringToFlags(undefined); }, TypeError);
47+
assert.throws(function() { fs._stringToFlags(null); }, TypeError);
48+
assert.throws(function() { fs._stringToFlags(assert); }, TypeError);
49+
assert.throws(function() { fs._stringToFlags([]); }, TypeError);
50+
assert.throws(function() { fs._stringToFlags({}); }, TypeError);
51+
52+
// Numeric flags that are not int will be passed to the binding, which
53+
// will throw a TypeError
54+
assert.throws(function() { fs.openSync('_', O_RDONLY + 0.1); }, TypeError);

0 commit comments

Comments
 (0)