From c61cb99a45de8d400f7294e3822eb47ea117da62 Mon Sep 17 00:00:00 2001 From: Dmytro Nechai Date: Tue, 20 Jun 2017 15:34:41 +0300 Subject: [PATCH] lib: make `safeRequire()` return tuple Refs: https://github.com/metarhia/jstp/pull/216 Closes: https://github.com/metarhia/jstp/issues/188 PR-URL: https://github.com/metarhia/jstp/pull/226 Reviewed-By: Denys Otrishko Reviewed-By: Mykola Bilochub Reviewed-By: Alexey Orlenko --- lib/common.js | 5 ++--- lib/record-serialization.js | 10 +++++++--- test/node/common-safe-require.js | 4 ++-- 3 files changed, 11 insertions(+), 8 deletions(-) diff --git a/lib/common.js b/lib/common.js index 2d7d5a4a..0c48c81e 100644 --- a/lib/common.js +++ b/lib/common.js @@ -31,10 +31,9 @@ common.forwardMultipleEvents = (from, to, eventNames) => { // common.safeRequire = (moduleName) => { try { - return require(moduleName); + return [null, require(moduleName)]; } catch (err) { - console.warn(err.toString()); - return null; + return [err, null]; } }; diff --git a/lib/record-serialization.js b/lib/record-serialization.js index 1f113594..b9655f69 100644 --- a/lib/record-serialization.js +++ b/lib/record-serialization.js @@ -12,9 +12,12 @@ module.exports = jsrs; // one of our priorities to optimize it. const USE_NATIVE_SERIALIZER = false; -const jstpNative = - safeRequire('../build/Release/jstp') || - safeRequire('../build/Debug/jstp'); +let [error, jstpNative] = safeRequire('../build/Release/jstp'); + +if (error) { + console.warn(error.toString()); + [error, jstpNative] = safeRequire('../build/Debug/jstp'); +} if (jstpNative) { Object.assign(jsrs, jstpNative); @@ -23,6 +26,7 @@ if (jstpNative) { } } else { console.warn( + error + '\n' + 'JSTP native addon is not built or is not functional. ' + 'Run `npm install` in order to build it, otherwise you will get ' + 'poor performance.' diff --git a/test/node/common-safe-require.js b/test/node/common-safe-require.js index 82a4206f..0a2375b7 100644 --- a/test/node/common-safe-require.js +++ b/test/node/common-safe-require.js @@ -7,7 +7,7 @@ const common = require('../../lib/common'); const existingModule = 'fs'; const nonExistingModule = '__non_existing_module__'; -test.ok(common.safeRequire(existingModule), 'must require existing module'); +test.ok(common.safeRequire(existingModule)[1], 'must require existing module'); -test.equal(common.safeRequire(nonExistingModule), null, +test.equal(common.safeRequire(nonExistingModule)[1], null, 'must return \'null\' if module doesn\'t exist');