npm-which

raw JSON →
3.0.1 verified Sat Apr 25 auth: no javascript

Locates executables from locally or parent-installed node modules, similar to `which` but respecting npm's PATH. Version 3.0.1 is stable with no recent releases. Key differentiator: it is faster than shelling out to `npm bin` and works across the node_modules hierarchy, not just the current directory. Supports both async and sync APIs, and a CLI. Requires Node >=4.2.0, no runtime dependencies.

error TypeError: which is not a function
cause Calling the imported package as a function without providing cwd first.
fix
const which = require('npm-which')(cwd); then which(name);
error Error: cwd is required
cause Calling require('npm-which')() without arguments.
fix
Pass a cwd string: require('npm-which')(__dirname);
error Error: Cannot find module 'tape'
cause The executable is not installed in any node_modules in the hierarchy.
fix
Install the package locally: npm install tape; or ensure it is in a parent node_modules.
error npm-which: command not found
cause The package is not installed globally.
fix
npm install -g npm-which
breaking v2 removed the default export of a string; you must call require('npm-which')(cwd) to get the which function.
fix Use require('npm-which')(cwd) instead of require('npm-which').
deprecated Passing cwd as second argument (options.cwd) is deprecated in favor of supplying it to the factory function.
fix Call npmWhich(cwd) instead of npmWhich()(name, {cwd}).
gotcha cwd is required. If omitted, the function throws an error.
fix Always provide cwd: const which = require('npm-which')(process.cwd());
gotcha The package does not search global node_modules; only local hierarchy.
fix Use which(1) for global executables.
gotcha The function returns the first match, not all matches.
fix For multiple results, consider a different tool or iterate over PATH manually.
npm install npm-which
yarn add npm-which
pnpm add npm-which

Shows programmatic usage (async and sync) and CLI invocation.

import npmWhich from 'npm-which';

const cwd = process.cwd();
const which = npmWhich(cwd);

// Async
which('tape', (err, path) => {
  if (err) console.error(err.message);
  else console.log(path);
});

// Sync
const pathToTape = which.sync('tape');
console.log(pathToTape);

// CLI: npm-which tape