Skip to content

Commit

Permalink
lib: make safeRequire() return tuple
Browse files Browse the repository at this point in the history
Refs: #216
Closes: #188
PR-URL: #226
Reviewed-By: Denys Otrishko <shishugi@gmail.com>
Reviewed-By: Mykola Bilochub <nbelochub@gmail.com>
Reviewed-By: Alexey Orlenko <eaglexrlnk@gmail.com>
  • Loading branch information
nechaido committed Jun 22, 2017
1 parent 38fc11f commit 35c6a8c
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 8 deletions.
5 changes: 2 additions & 3 deletions lib/common.js
Original file line number Diff line number Diff line change
Expand Up @@ -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];
}
};

Expand Down
10 changes: 7 additions & 3 deletions lib/record-serialization.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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.'
Expand Down
4 changes: 2 additions & 2 deletions test/node/common-safe-require.js
Original file line number Diff line number Diff line change
Expand Up @@ -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');

0 comments on commit 35c6a8c

Please sign in to comment.