UNPKG

2.21 kBJavaScriptView Raw
1/**
2 * Loader for `$invoke`.
3 * Using `findout` package to findout modules.
4 * @memberof module:apeman-commons-invocating/lib
5 * @inner
6 * @constructor InvocationLoader
7 * @param {object} config - Loader configuration.
8 * @see https://github.com/okunishinishi/node-findout
9 */
10
11"use strict";
12
13var findout = require('findout'),
14 extend = require('extend');
15
16/** @lends InvocationLoader */
17function InvocationLoader() {
18 var s = this;
19 s.init.apply(s, arguments);
20}
21
22InvocationLoader.prototype = {
23 /** @construct InvocationLoader */
24 init: function (config) {
25 var s = this;
26 extend(s, config);
27 },
28 /**
29 * Base directory path.
30 * @type {string}
31 */
32 basedir: process.cwd(),
33 /**
34 * Load a module.
35 * Works like `require()`, but has a lot more locations to search.
36 * @param {string} name - Name to module.
37 * @param {function} callback - Callback when done.
38 */
39 load: function (name, callback) {
40 var s = this;
41 var module = s.resolve(name);
42 if (module) {
43 callback(null, require(module));
44 } else {
45 callback(new Error('Module not found: ' + name));
46 }
47 },
48 /**
49 * Resolve a module.
50 * Works like `require.resolve()`, but has a lot more locations to search.
51 * @param {string} name - Name to module.
52 * @returns {*}
53 */
54 resolve: function (name) {
55 var s = this;
56 var dirnames = [s.basedir, null];
57 for (var i = 0, len = dirnames.length; i < len; i++) {
58 try {
59 var resolved = findout.resolve(name, {
60 cwd: dirnames[i]
61 });
62 if (resolved) {
63 return resolved;
64 }
65 } catch (e) {
66 // Do nothing.
67 }
68 }
69 return null;
70 }
71};
72
73/**
74 * Define a module loader.
75 * @param {object} properties - Prototype properties.
76 * @returns {function} - Module loader constructor.
77 */
78InvocationLoader.define = function (properties) {
79 function Defined() {
80
81 }
82
83 Defined.prototype = new InvocationLoader(properties);
84
85 return Defined;
86};
87
88module.exports = InvocationLoader;
\No newline at end of file