index.js
 1  'use strict';
 2  const path = require('path');
 3  const Module = require('module');
 4  const fs = require('fs');
 5  
 6  const resolveFrom = (fromDirectory, moduleId, silent) => {
 7  	if (typeof fromDirectory !== 'string') {
 8  		throw new TypeError(`Expected \`fromDir\` to be of type \`string\`, got \`${typeof fromDirectory}\``);
 9  	}
10  
11  	if (typeof moduleId !== 'string') {
12  		throw new TypeError(`Expected \`moduleId\` to be of type \`string\`, got \`${typeof moduleId}\``);
13  	}
14  
15  	try {
16  		fromDirectory = fs.realpathSync(fromDirectory);
17  	} catch (error) {
18  		if (error.code === 'ENOENT') {
19  			fromDirectory = path.resolve(fromDirectory);
20  		} else if (silent) {
21  			return;
22  		} else {
23  			throw error;
24  		}
25  	}
26  
27  	const fromFile = path.join(fromDirectory, 'noop.js');
28  
29  	const resolveFileName = () => Module._resolveFilename(moduleId, {
30  		id: fromFile,
31  		filename: fromFile,
32  		paths: Module._nodeModulePaths(fromDirectory)
33  	});
34  
35  	if (silent) {
36  		try {
37  			return resolveFileName();
38  		} catch (error) {
39  			return;
40  		}
41  	}
42  
43  	return resolveFileName();
44  };
45  
46  module.exports = (fromDirectory, moduleId) => resolveFrom(fromDirectory, moduleId);
47  module.exports.silent = (fromDirectory, moduleId) => resolveFrom(fromDirectory, moduleId, true);