|
| 1 | +import * as cp from "child_process"; |
1 | 2 | import * as crypto from "crypto";
|
2 | 3 | import * as fs from "fs";
|
3 | 4 | import * as os from "os";
|
@@ -76,3 +77,40 @@ export const getMediaMime = (filePath?: string): string => {
|
76 | 77 | ".json": "application/json",
|
77 | 78 | }[extname(filePath)]) || "text/plain";
|
78 | 79 | };
|
| 80 | + |
| 81 | +export const isWsl = async (): Promise<boolean> => { |
| 82 | + return process.platform === "linux" |
| 83 | + && os.release().toLowerCase().indexOf("microsoft") !== -1 |
| 84 | + || (await util.promisify(fs.readFile)("/proc/version", "utf8")) |
| 85 | + .toLowerCase().indexOf("microsoft") !== -1; |
| 86 | +}; |
| 87 | + |
| 88 | +export const open = async (url: string): Promise<void> => { |
| 89 | + let command: string; |
| 90 | + const args = <string[]>[]; |
| 91 | + const options = <cp.SpawnOptions>{}; |
| 92 | + const platform = await isWsl() ? "wsl" : process.platform; |
| 93 | + switch (platform) { |
| 94 | + case "darwin": |
| 95 | + command = "open"; |
| 96 | + break; |
| 97 | + case "win32": |
| 98 | + case "wsl": |
| 99 | + command = platform === "wsl" ? "cmd.exe" : "cmd"; |
| 100 | + args.push("/c", "start", '""', "/b"); |
| 101 | + url = url.replace(/&/g, "^&"); |
| 102 | + default: |
| 103 | + command = "xdg-open"; |
| 104 | + break; |
| 105 | + } |
| 106 | + args.push(url); |
| 107 | + const proc = cp.spawn(command, args, options); |
| 108 | + await new Promise((resolve, reject) => { |
| 109 | + proc.on("error", reject); |
| 110 | + proc.on("close", (code) => { |
| 111 | + return code !== 0 |
| 112 | + ? reject(new Error(`Failed to open with code ${code}`)) |
| 113 | + : resolve(); |
| 114 | + }); |
| 115 | + }); |
| 116 | +}; |
0 commit comments