index.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /**
  2. * Module dependencies.
  3. */
  4. var sep = require('path').sep || '/';
  5. /**
  6. * Module exports.
  7. */
  8. module.exports = fileUriToPath;
  9. /**
  10. * File URI to Path function.
  11. *
  12. * @param {String} uri
  13. * @return {String} path
  14. * @api public
  15. */
  16. function fileUriToPath (uri) {
  17. if ('string' != typeof uri ||
  18. uri.length <= 7 ||
  19. 'file://' != uri.substring(0, 7)) {
  20. throw new TypeError('must pass in a file:// URI to convert to a file path');
  21. }
  22. var rest = decodeURI(uri.substring(7));
  23. var firstSlash = rest.indexOf('/');
  24. var host = rest.substring(0, firstSlash);
  25. var path = rest.substring(firstSlash + 1);
  26. // 2. Scheme Definition
  27. // As a special case, <host> can be the string "localhost" or the empty
  28. // string; this is interpreted as "the machine from which the URL is
  29. // being interpreted".
  30. if ('localhost' == host) host = '';
  31. if (host) {
  32. host = sep + sep + host;
  33. }
  34. // 3.2 Drives, drive letters, mount points, file system root
  35. // Drive letters are mapped into the top of a file URI in various ways,
  36. // depending on the implementation; some applications substitute
  37. // vertical bar ("|") for the colon after the drive letter, yielding
  38. // "file:///c|/tmp/test.txt". In some cases, the colon is left
  39. // unchanged, as in "file:///c:/tmp/test.txt". In other cases, the
  40. // colon is simply omitted, as in "file:///c/tmp/test.txt".
  41. path = path.replace(/^(.+)\|/, '$1:');
  42. // for Windows, we need to invert the path separators from what a URI uses
  43. if (sep == '\\') {
  44. path = path.replace(/\//g, '\\');
  45. }
  46. if (/^.+\:/.test(path)) {
  47. // has Windows drive at beginning of path
  48. } else {
  49. // unix path…
  50. path = sep + path;
  51. }
  52. return host + path;
  53. }