1 | "use strict";
|
2 |
|
3 |
|
4 | const path = require('path');
|
5 | const fs = require('fs');
|
6 |
|
7 | var modules = {};
|
8 | var packages_paths = {};
|
9 |
|
10 | function findPackage(file_path) {
|
11 | file_path = path.resolve(file_path);
|
12 | var paths = file_path.split(path.sep);
|
13 | if(packages_paths[file_path])
|
14 | return packages_paths[file_path];
|
15 |
|
16 | for(var n = paths.length - 1; n > 0; n--) {
|
17 | var package_path = (paths.slice(0, n).concat("package.json")).join(path.sep);
|
18 | if(fs.existsSync(package_path))
|
19 | return packages_paths[file_path] = package_path;
|
20 | }
|
21 |
|
22 | throw `can't find ${file_path} package`;
|
23 | }
|
24 |
|
25 | module.exports = function(file_path) {
|
26 | var package_path = findPackage(file_path);
|
27 | if(modules[package_path])
|
28 | return modules[package_path];
|
29 | var module = require(package_path);
|
30 | module.package_path = package_path;
|
31 | return modules[package_path] = module;
|
32 | };
|