Last active
February 28, 2018 11:26
-
-
Save LM1LC3N7/a7544b29400363a0b79ee552f01f3f4b to your computer and use it in GitHub Desktop.
Require a module and catch errors when it is not installed nor finded
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// To test this: | |
// 1) node requireHandleErrors.js | |
// | |
// Output should be: | |
// $ node requireHandleErrors.js | |
// Module "moduleNotFound" not found. Maybe it is not installed yet? | |
// | |
// | |
// Source: https://stackoverflow.com/a/34005010 | |
// https://stackoverflow.com/a/38885374 | |
// | |
let assert = require('assert'); | |
// | |
// New function to require a module | |
// and handle require errors | |
// | |
// Input: module name or path | |
// Output: module content, like "require()" | |
// | |
function requireModule (modulePath) { | |
assert.equal(typeof (modulePath), 'string', 'Argument "modulePath" must be a string.'); | |
try { | |
return require(modulePath); | |
} catch (error) { | |
if (error.code !== 'MODULE_NOT_FOUND') { | |
throw error; | |
} else { | |
console.error('Module "' + modulePath + '" not found. Maybe it is not installed yet?'); | |
} | |
} | |
} | |
// Test to require an unknown module | |
let moduleNotFound = requireModule('moduleNotFound'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment