UNPKG

891 BJavaScriptView Raw
1"use strict";
2
3//return the module a file belong to
4const path = require('path');
5const fs = require('fs');
6
7var modules = {};
8var packages_paths = {}; //cache
9
10function 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
25module.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};