From 493864a52628f67aaa94e603613ac6041ad215f4 Mon Sep 17 00:00:00 2001 From: Sam Roberts Date: Sun, 13 Sep 2015 15:11:17 +0100 Subject: [PATCH] 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: https://github.com/nodejs/node/pull/2902 Reviewed-By: Ben Noordhuis --- lib/fs.js | 7 ++++--- test/parallel/test-fs-open-flags.js | 14 ++++++++++++++ 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/lib/fs.js b/lib/fs.js index eeb3806cdc8861..f9f104eb229994 100644 --- a/lib/fs.js +++ b/lib/fs.js @@ -465,10 +465,11 @@ fs.readFileSync = function(path, options) { // Used by binding.open and friends function stringToFlags(flag) { - // Only mess with strings - if (typeof flag !== 'string') { + if (typeof flag === 'number') return flag; - } + + if (typeof flag !== 'string') + throw new TypeError('flag must be a string'); switch (flag) { case 'r' : return O_RDONLY; diff --git a/test/parallel/test-fs-open-flags.js b/test/parallel/test-fs-open-flags.js index c7d53117d587fc..0070e3011d8ba2 100644 --- a/test/parallel/test-fs-open-flags.js +++ b/test/parallel/test-fs-open-flags.js @@ -38,3 +38,17 @@ assert.equal(fs._stringToFlags('xa+'), O_APPEND | O_CREAT | O_RDWR | O_EXCL); 'x +x x+ rx rx+ wxx wax xwx xxx').split(' ').forEach(function(flags) { assert.throws(function() { fs._stringToFlags(flags); }); }); + +// Use of numeric flags is permitted. +assert.equal(fs._stringToFlags(O_RDONLY), O_RDONLY); + +// Non-numeric/string flags are a type error. +assert.throws(function() { fs._stringToFlags(undefined); }, TypeError); +assert.throws(function() { fs._stringToFlags(null); }, TypeError); +assert.throws(function() { fs._stringToFlags(assert); }, TypeError); +assert.throws(function() { fs._stringToFlags([]); }, TypeError); +assert.throws(function() { fs._stringToFlags({}); }, TypeError); + +// Numeric flags that are not int will be passed to the binding, which +// will throw a TypeError +assert.throws(function() { fs.openSync('_', O_RDONLY + 0.1); }, TypeError);