Debian Codegraph @

ncjsm/resolve/sync.js

raw
1 // Sync module resolver
2
3 "use strict";
4
5 const { resolve } = require("path")
6 , PassThru = require("../utils/pass-thru")
7 , getResolver = require("../lib/get-node-resolver");
8
9 const { statSync: stat, readFileSync: readFile, realpathSync: realpath } = require("fs");
10
11 const { parse } = JSON;
12
13 const resolver = getResolver(
14 targetPath => {
15 let stats;
16 targetPath = resolve(targetPath);
17 try {
18 stats = stat(targetPath);
19 } catch (e) {
20 if (e.code === "ENOENT") return new PassThru(null);
21 throw e;
22 }
23 if (stats.isFile()) return new PassThru({ targetPath, realPath: realpath(targetPath) });
24 return new PassThru(null);
25 },
26 path => {
27 let data, result;
28 try {
29 data = readFile(resolve(path, "package.json"));
30 } catch (e) {
31 if (e.code === "ENOENT") return new PassThru(null);
32 throw e;
33 }
34 try { result = parse(data).main; }
35 catch (e) { result = null; }
36 return new PassThru(result);
37 }
38 );
39
40 module.exports = function (dir, path, options = {}) { return resolver(dir, path, options).value; };