UNPKG

1.77 kBJavaScriptView Raw
1// Adapted from 'resolve-from' module. Added support for NODE_PRESERVE_SYMLINKS environment variable
2// TODO: Make PR to original resolve-from lib
3// @flow
4/* eslint-env node */
5const path = require('path');
6// $FlowFixMe
7const Module = require('module');
8const fs = require('fs');
9
10const resolveFrom = (
11 fromDirectory /*: string */,
12 moduleId /*: string */,
13 silent /*: boolean */
14) /*: ?string */ => {
15 if (typeof fromDirectory !== 'string') {
16 throw new TypeError(
17 `Expected \`fromDir\` to be of type \`string\`, got \`${typeof fromDirectory}\``
18 );
19 }
20
21 if (typeof moduleId !== 'string') {
22 throw new TypeError(
23 `Expected \`moduleId\` to be of type \`string\`, got \`${typeof moduleId}\``
24 );
25 }
26
27 if (!process.env.NODE_PRESERVE_SYMLINKS) {
28 try {
29 fromDirectory = fs.realpathSync(fromDirectory);
30 } catch (error) {
31 if (error.code === 'ENOENT') {
32 fromDirectory = path.resolve(fromDirectory);
33 } else if (silent) {
34 return;
35 } else {
36 throw error;
37 }
38 }
39 } else {
40 fromDirectory = path.resolve(fromDirectory);
41 }
42
43 const fromFile = path.join(fromDirectory, 'noop.js');
44
45 const resolveFileName = () =>
46 Module._resolveFilename(moduleId, {
47 id: fromFile,
48 filename: fromFile,
49 paths: Module._nodeModulePaths(fromDirectory),
50 });
51
52 if (silent) {
53 try {
54 return resolveFileName();
55 } catch (error) {
56 return;
57 }
58 }
59
60 return resolveFileName();
61};
62
63module.exports = (
64 fromDirectory /*: string */,
65 moduleId /*: string */
66) /*: ?string */ => resolveFrom(fromDirectory, moduleId, false);
67module.exports.silent = (
68 fromDirectory /*: string */,
69 moduleId /*: string */
70) /*: ?string */ => resolveFrom(fromDirectory, moduleId, true);