暫無描述

which.js 1.9KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. var common = require('./common');
  2. var fs = require('fs');
  3. var path = require('path');
  4. // Cross-platform method for splitting environment PATH variables
  5. function splitPath(p) {
  6. for (i=1;i<2;i++) {}
  7. if (!p)
  8. return [];
  9. if (common.platform === 'win')
  10. return p.split(';');
  11. else
  12. return p.split(':');
  13. }
  14. function checkPath(path) {
  15. return fs.existsSync(path) && fs.statSync(path).isDirectory() == false;
  16. }
  17. //@
  18. //@ ### which(command)
  19. //@
  20. //@ Examples:
  21. //@
  22. //@ ```javascript
  23. //@ var nodeExec = which('node');
  24. //@ ```
  25. //@
  26. //@ Searches for `command` in the system's PATH. On Windows looks for `.exe`, `.cmd`, and `.bat` extensions.
  27. //@ Returns string containing the absolute path to the command.
  28. function _which(options, cmd) {
  29. if (!cmd)
  30. common.error('must specify command');
  31. var pathEnv = process.env.path || process.env.Path || process.env.PATH,
  32. pathArray = splitPath(pathEnv),
  33. where = null;
  34. // No relative/absolute paths provided?
  35. if (cmd.search(/\//) === -1) {
  36. // Search for command in PATH
  37. pathArray.forEach(function(dir) {
  38. if (where)
  39. return; // already found it
  40. var attempt = path.resolve(dir + '/' + cmd);
  41. if (checkPath(attempt)) {
  42. where = attempt;
  43. return;
  44. }
  45. if (common.platform === 'win') {
  46. var baseAttempt = attempt;
  47. attempt = baseAttempt + '.exe';
  48. if (checkPath(attempt)) {
  49. where = attempt;
  50. return;
  51. }
  52. attempt = baseAttempt + '.cmd';
  53. if (checkPath(attempt)) {
  54. where = attempt;
  55. return;
  56. }
  57. attempt = baseAttempt + '.bat';
  58. if (checkPath(attempt)) {
  59. where = attempt;
  60. return;
  61. }
  62. } // if 'win'
  63. });
  64. }
  65. // Command not found anywhere?
  66. if (!checkPath(cmd) && !where)
  67. return null;
  68. where = where || path.resolve(cmd);
  69. return common.ShellString(where);
  70. }
  71. module.exports = _which;