index.js 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. import process from 'node:process';
  2. import path from 'node:path';
  3. import url from 'node:url';
  4. import pathKey from 'path-key';
  5. export function npmRunPath(options = {}) {
  6. const {
  7. cwd = process.cwd(),
  8. path: path_ = process.env[pathKey()],
  9. execPath = process.execPath,
  10. } = options;
  11. let previous;
  12. const execPathString = execPath instanceof URL ? url.fileURLToPath(execPath) : execPath;
  13. const cwdString = cwd instanceof URL ? url.fileURLToPath(cwd) : cwd;
  14. let cwdPath = path.resolve(cwdString);
  15. const result = [];
  16. while (previous !== cwdPath) {
  17. result.push(path.join(cwdPath, 'node_modules/.bin'));
  18. previous = cwdPath;
  19. cwdPath = path.resolve(cwdPath, '..');
  20. }
  21. // Ensure the running `node` binary is used.
  22. result.push(path.resolve(cwdString, execPathString, '..'));
  23. return [...result, path_].join(path.delimiter);
  24. }
  25. export function npmRunPathEnv({env = process.env, ...options} = {}) {
  26. env = {...env};
  27. const path = pathKey({env});
  28. options.path = env[path];
  29. env[path] = npmRunPath(options);
  30. return env;
  31. }