From d637b1ba49c3fd047b63765876647d0545710454 Mon Sep 17 00:00:00 2001 From: Cory Snider Date: Mon, 20 Aug 2018 16:32:44 -0400 Subject: [PATCH] Normalize `null` options correctly Fixes #227. The first version of Node where FS functions accepted an options object was version 0.10. Between Node 0.10 and Node 6 inclusive, all falsy values (including the empty string) and functions are replaced with the default options. Only truthy values which are not strings, objects or functions throw a `TypeError`. Node 7 introduced a breaking change: only `null`, `undefined` and functions get replaced with the default options, and any values which are not strings or objects throw a `TypeError`. https://github.com/nodejs/node/pull/7165/files#diff-9a205ef7ee967ee32efee02e58b3482dR39 It is not clear which version of the Node FS API is emulated by BrowserFS, so I have elected to implement the Node 7 behaviour. --- src/core/FS.ts | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/core/FS.ts b/src/core/FS.ts index 5120e7a5..5e62a9bd 100644 --- a/src/core/FS.ts +++ b/src/core/FS.ts @@ -77,7 +77,8 @@ function normalizePath(p: string): string { * @hidden */ function normalizeOptions(options: any, defEnc: string | null, defFlag: string, defMode: number | null): {encoding: string; flag: string; mode: number} { - switch (typeof options) { + // typeof null === 'object' so special-case handing is needed. + switch (options === null ? 'null' : typeof options) { case 'object': return { encoding: typeof options['encoding'] !== 'undefined' ? options['encoding'] : defEnc, @@ -90,12 +91,16 @@ function normalizeOptions(options: any, defEnc: string | null, defFlag: string, flag: defFlag, mode: defMode! }; - default: + case 'null': + case 'undefined': + case 'function': return { encoding: defEnc!, flag: defFlag, mode: defMode! }; + default: + throw new TypeError(`"options" must be a string or an object, got ${typeof options} instead.`); } }