Skip to content

Instantly share code, notes, and snippets.

@LM1LC3N7
Last active February 28, 2018 11:26
Show Gist options
  • Save LM1LC3N7/a7544b29400363a0b79ee552f01f3f4b to your computer and use it in GitHub Desktop.
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
//
// 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