diff --git a/lib/common.js b/lib/common.js index f3ee36c3..67e801ca 100644 --- a/lib/common.js +++ b/lib/common.js @@ -25,3 +25,14 @@ common.forwardMultipleEvents = (from, to, eventNames) => { common.forwardEvent(from, to, event); }); }; + +// Try to require `moduleName` and return the exported object if the module is +// found or null otherwise. +// +common.safeRequire = (moduleName) => { + try { + return require(moduleName); + } catch (err) { + return null; + } +}; diff --git a/lib/record-serialization.js b/lib/record-serialization.js index 61406117..3bc21330 100644 --- a/lib/record-serialization.js +++ b/lib/record-serialization.js @@ -1,5 +1,6 @@ 'use strict'; +const safeRequire = require('./common').safeRequire; const serializerFactory = require('./serializer-factory'); const jsrs = {}; @@ -11,26 +12,20 @@ module.exports = jsrs; // one of our priorities to optimize it. const USE_NATIVE_SERIALIZER = false; -let jstpNative; - -try { - jstpNative = require('../build/Release/jstp'); -} catch (e) { - try { - jstpNative = require('../build/Debug/jstp'); - } catch (e) { - console.warn( - 'JSTP native addon is not built. ' + - 'Run `npm install` in order to build it, otherwise you will get ' + - 'poor server performance under load.' - ); - module.exports = require('./record-serialization-fallback'); - } -} +const jstpNative = + safeRequire('../build/Release/jstp') || + safeRequire('../build/Debug/jstp'); if (jstpNative) { Object.assign(jsrs, jstpNative); if (!USE_NATIVE_SERIALIZER) { jsrs.stringify = serializerFactory.createSerializer(); } +} else { + console.warn( + 'JSTP native addon is not built. ' + + 'Run `npm install` in order to build it, otherwise you will get ' + + 'poor server performance under load.' + ); + module.exports = require('./record-serialization-fallback'); }