Resolve the path of a module like require.resolve() but from the current working directory
npx @tessl/cli install tessl/npm-resolve-cwd@3.0.0Resolve CWD provides a simple utility for resolving module paths from the current working directory. It wraps Node.js's module resolution system to resolve modules relative to process.cwd() instead of the calling file's location, making it useful for CLI tools, build systems, and other utilities that need to resolve modules from a specific working context.
npm install resolve-cwdconst resolveCwd = require('resolve-cwd');For ESM:
import resolveCwd from 'resolve-cwd';For TypeScript:
import resolveCwd = require('resolve-cwd');const resolveCwd = require('resolve-cwd');
console.log(__dirname);
//=> '/Users/sindresorhus/rainbow'
console.log(process.cwd());
//=> '/Users/sindresorhus/unicorn'
console.log(resolveCwd('./foo'));
//=> '/Users/sindresorhus/unicorn/foo.js'
// Silent variant - returns undefined instead of throwing
console.log(resolveCwd.silent('./nonexistent'));
//=> undefinedResolves the path of a module from the current working directory, similar to require.resolve() but using process.cwd() as the base directory.
/**
* Resolve the path of a module from the current working directory
* @param moduleId - What you would use in require()
* @returns The resolved module path
* @throws When the module can't be found
*/
resolveCwd(moduleId: string): string;Usage Examples:
const resolveCwd = require('resolve-cwd');
// Resolve relative path from current working directory
const localModule = resolveCwd('./lib/utils');
//=> '/current/working/dir/lib/utils.js'
// Resolve npm package from current working directory's node_modules
const packagePath = resolveCwd('lodash');
//=> '/current/working/dir/node_modules/lodash/index.js'
// Resolve with file extension
const jsFile = resolveCwd('./config.json');
//=> '/current/working/dir/config.json'Resolves the path of a module from the current working directory without throwing errors. Returns undefined when the module cannot be found.
/**
* Resolve the path of a module from the current working directory (silent)
* @param moduleId - What you would use in require()
* @returns The resolved module path or undefined if not found
*/
resolveCwd.silent(moduleId: string): string | undefined;Usage Examples:
const resolveCwd = require('resolve-cwd');
// Safe resolution - no error thrown
const existingModule = resolveCwd.silent('./existing-file');
//=> '/current/working/dir/existing-file.js'
const nonExistentModule = resolveCwd.silent('./nonexistent');
//=> undefined
// Useful for optional dependencies
const optionalConfig = resolveCwd.silent('./optional-config.js');
if (optionalConfig) {
// Load optional configuration
const config = require(optionalConfig);
}The main resolveCwd() function throws standard Node.js module resolution errors when a module cannot be found:
The resolveCwd.silent() variant never throws and returns undefined for any resolution failures.