UNPKG

requirefresh

Version:

Require a file without adding it into the require cache

63 lines (62 loc) 2.27 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.requireFreshPromise = exports.requireFreshSafe = exports.requireFreshCallback = exports.requireFresh = void 0; const path_1 = require("path"); /** * Require the path without any caching. * @param path the path to require * @returns the result of the `require` call * @throws note that the `require` call may throw if something went wrong requiring the path */ function requireFresh(path) { // Resolve the path to the one used for the cache const resolvedPath = (0, path_1.resolve)(path); // Attempt require with removals of the cache delete require.cache[resolvedPath]; // clear require cache for the config file const result = require(resolvedPath); delete require.cache[resolvedPath]; // clear require cache for the config file // Return result return result; } exports.requireFresh = requireFresh; // alias exports.default = requireFresh; /** * Require the path without any caching, but catch errors into the callback. * Error cannot be returned because what if the module intended to RETURN (not throw) an error, hence why callback is used, as it can differentiate between returned and thrown errors. * @param path the path to require * @param next the callback * @returns {void} */ function requireFreshCallback(path, next) { let result, error; try { result = requireFresh(path); } catch (err) { error = err; } next(error, result); } exports.requireFreshCallback = requireFreshCallback; // b/c alias exports.requireFreshSafe = requireFreshCallback; /** * Require the path without any caching, but catch errors into the callback. * Error cannot be returned because what if the module intended to RETURN (not throw) an error, hence why promise is used, as it can differentiate between returned and thrown errors. * @param path the path to require * @returns {void} */ function requireFreshPromise(path) { return new Promise(function (resolve, reject) { let result; try { result = requireFresh(path); } catch (err) { return reject(err); } resolve(result); }); } exports.requireFreshPromise = requireFreshPromise;