How to use the silent function from resolve-from

Find comprehensive JavaScript resolve-from.silent code examples handpicked from public code repositorys.

resolve-from.silent is a Node.js module that resolves a module's path without throwing an error if the module cannot be found.

35
36
37
38
39
40
41
42
43
44
 * @returns {AnalyzeResult}
 */
module.exports.analyze = async function analyze(modul) {
  console.info(`[Analyzer.js] analyzing ${modul.path}`);
  await init();
  resolve = resolveFrom.silent.bind(null, path.dirname(modul.path));
  await traverse(modul);
  console.debug(`[Analyzer.js] ${modul.path} has scope variables ${vars}`);
  console.debug(
    `[Analyzer.js] ${modul.path} has scope assignments ${assignments}`
fork icon6
star icon20
watch icon4

+ 9 other calls in file

How does resolve-from.silent work?

resolve-from.silent works similarly to Node.js' built-in require.resolve() function, but it doesn't throw an error if the module cannot be found. Instead, it returns null if the module cannot be resolved.

The function takes two arguments: a base directory to start the module search from, and the name or path of the module to be resolved. It uses Node.js' module resolution algorithm to find the module, starting from the specified directory. If the module is found, it returns the resolved path to the module. If the module cannot be found, it returns null.

resolve-from.silent can be useful in scenarios where you want to check if a module exists without triggering an error. For example, you might want to conditionally require a module only if it exists.

Ai Example

1
2
3
4
5
const resolveFromSilent = require("resolve-from").silent;

const path = resolveFromSilent(__dirname, "nonexistent-module");

console.log(path); // Outputs null

In this example, resolveFromSilent is used to try to resolve the module nonexistent-module relative to the current directory (__dirname). Since the module does not exist, resolveFromSilent returns null.