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