1 | const co = require('co');
|
2 | const fs = require('mz/fs');
|
3 | const got = require('got');
|
4 | const is = require('is_js');
|
5 | const path = require('path');
|
6 | const R = require('ramda');
|
7 | const requireString = require('@panosoft/require-string');
|
8 | const url = require('url');
|
9 |
|
10 | const isUrl = path => !!url.parse(path).hostname;
|
11 | const resolvePath = filePath => isUrl(filePath) ?
|
12 | filePath:
|
13 | path.resolve(filePath);
|
14 | const loadUrl = url => got(url).then(R.prop('body'));
|
15 | const loadFile = path => isUrl(path) ?
|
16 | loadUrl(path):
|
17 | fs.readFile(path, 'utf8');
|
18 | const loadModule = (content, resolvedPath) => {
|
19 | const filename = isUrl(resolvedPath) ? path.resolve(path.basename(resolvedPath)) : resolvedPath;
|
20 | return requireString(content, filename);
|
21 | };
|
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 |
|
31 | const load = co.wrap(function * (path) {
|
32 | if (!is.string(path)) throw new TypeError('path: must be a string.');
|
33 | const resolvedPath = resolvePath(path);
|
34 | const contents = yield loadFile(resolvedPath);
|
35 | return loadModule(contents, resolvedPath);
|
36 | });
|
37 |
|
38 | module.exports = { load };
|