Maik 79c46dcb5d modul | hace 3 años | |
---|---|---|
.. | ||
README.md | hace 3 años | |
index.js | hace 3 años | |
package.json | hace 3 años |
NodeJS Require that let you handle module not found error without try/catch. Allows you to gracefully require a module only if it exists and contains no error.
const optionalRequire = require("optional-require")(require);
const foo = optionalRequire("foo") || {};
const bar = optionalRequire("bar", true); // true enables console.log a message when not found
const xyz = optionalRequire("xyz", "test"); // "test" enables console.log a message with "test" added.
const fbPath = optionalRequire.resolve("foo", "foo doesn't exist");
const rel = optionalRequire("../foo/bar"); // relative module path works
$ npm i optional-require --save
The single function this module exports. Call it with require
to get a custom function for you to do optional require from your file's require context. See Usage above.
The function optionalRequire returns for you to do optional require from your file's require context.
path
- name/path to the module your want to optionally requiremessage
- optional flag/message to enable console.log
a message when module is not foundoptions
- an optional object with the following fields
message
- see abovefail
- callback for when an error that's not MODULE_NOT_FOUND
for path
occurrednotFound
- callback for when path
was not found
default
- default value to returned when not found - not allowed with notFound
togetherundefined
oroptions.notFound
if it's specifiedoptions.default
if it's specifiedMODULE_NOT_FOUND
for the module path
Same as customOptionalRequire but acts like require.resolve
The function that will be called to log the message when optional module is not found. You can override this with your own function.
Same as customOptionalRequire but you have to pass in require
from your file's context.
Same as customOptionalRequire.resolve but you have to pass in require
from your file's context.
Apache-2.0 © Joel Chen