UNPKG

2.15 kBPlain TextView Raw
1import { resolve } from 'https://deno.land/std/node/path.ts'
2
3/**
4 * Require Fresh Callback in typical errback style.
5 * @param error if the `require` call threw, this is its error
6 * @param result if the `require` call performed succesfully, this is its result
7 */
8export type Errback = (error: Error | undefined, result: any) => any
9
10/**
11 * Require the path without any caching.
12 * @param path the path to require
13 * @returns the result of the `require` call
14 * @throws note that the `require` call may throw if something went wrong requiring the path
15 */
16export function requireFresh(path: string) {
17 // Resolve the path to the one used for the cache
18 const resolvedPath = resolve(path)
19
20 // Attempt require with removals of the cache
21 delete require.cache[resolvedPath] // clear require cache for the config file
22 const result = require(resolvedPath)
23 delete require.cache[resolvedPath] // clear require cache for the config file
24
25 // Return result
26 return result
27}
28
29// alias
30export default requireFresh
31
32/**
33 * Require the path without any caching, but catch errors into the callback.
34 * 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.
35 * @param path the path to require
36 * @param next the callback
37 * @returns {void}
38 */
39export function requireFreshCallback(path: string, next: Errback) {
40 let result, error
41 try {
42 result = requireFresh(path)
43 } catch (err) {
44 error = err
45 }
46 next(error, result)
47}
48// b/c alias
49export const requireFreshSafe = requireFreshCallback
50
51/**
52 * Require the path without any caching, but catch errors into the callback.
53 * 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.
54 * @param path the path to require
55 * @returns {void}
56 */
57export function requireFreshPromise(path: string) {
58 return new Promise(function (resolve, reject) {
59 let result
60 try {
61 result = requireFresh(path)
62 } catch (err) {
63 return reject(err)
64 }
65 resolve(result)
66 })
67}