-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathisomorphic.node.ts
37 lines (31 loc) · 1017 Bytes
/
isomorphic.node.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/* eslint-env node */
/// <reference types="node" />
/// <reference lib="dom" />
import * as path from "path";
import { pathToFileURL } from "url";
// Tests whether a string is an absolute URL
const absoluteUrlPattern = /^(\w{2,}):\/\//;
/**
* Returns the current working directory as a "file://" URL
*/
export function getCWD(): string {
return process.cwd();
}
/**
* In Node.js, we allow file locations to be specified as a filesystem path or as a URL.
* This function disambiguates those and returns a parsed "file://" or "http(s)://" URL.
*/
export function locationToURL(location: string | URL, cwd?: string): URL {
if (location instanceof URL) {
return location;
}
else if (absoluteUrlPattern.test(location)) {
// Looks like the location is a URL, so parse it to ensure it's valid
return new URL(location);
}
else {
// Looks like this is a local filesystem path
let absolutePath = path.resolve(cwd || getCWD(), location);
return pathToFileURL(absolutePath);
}
}