UNPKG

1.28 kBJavaScriptView Raw
1const co = require('co');
2const fs = require('mz/fs');
3const got = require('got');
4const is = require('is_js');
5const path = require('path');
6const R = require('ramda');
7const requireString = require('@panosoft/require-string');
8const url = require('url');
9
10const isUrl = path => !!url.parse(path).hostname;
11const resolvePath = filePath => isUrl(filePath) ?
12 filePath:
13 path.resolve(filePath);
14const loadUrl = url => got(url).then(R.prop('body'));
15const loadFile = path => isUrl(path) ?
16 loadUrl(path):
17 fs.readFile(path, 'utf8');
18const loadModule = (content, resolvedPath) => {
19 const filename = isUrl(resolvedPath) ? path.resolve(path.basename(resolvedPath)) : resolvedPath;
20 return requireString(content, filename);
21};
22/**
23 * Loads a js module from a local or remote path.
24 *
25 * @param {String} path
26 * - fully qualified uri (i.e. http://test.com/file.txt)
27 * - absolute path (i.e. /path/to/module.js)
28 * - relative path (i.e. starting with ./ or ../ or path/)
29 * @returns {*} module exports
30 */
31const 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
38module.exports = { load };