-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnpm.js
68 lines (52 loc) · 1.79 KB
/
npm.js
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import { fork } from "node:child_process";
import console from "console-ansi";
import { execCommand } from "./utils.js";
const substringAfterChar = (string, char) =>
string.substring(string.indexOf(char));
const quotes = ['"', "'"];
const stripQuotes = (s) =>
quotes.includes(s.charAt(0)) && quotes.includes(s.charAt(s.length - 1))
? s.substr(1, s.length - 2)
: s;
class Npm {
process = null;
processEnv = null;
patch = true;
defaultArgv = ["--progress=false"];
async load(npmPath) {
this.npmPath = npmPath;
// Freeze the initial env as running npm modifies it
this.processEnv = { ...process.env };
}
async run(npmRoot, cmd, argv = []) {
let stdout;
const json = argv.includes("--json");
if (this.npmPath) {
const child = fork(
this.npmPath,
[cmd, ...argv.map(stripQuotes), ...this.defaultArgv],
{ env: this.processEnv, stdio: [null, null, null, "ipc"] },
);
stdout = "";
let stderr = "";
for await (const chunk of child.stdout) stdout += chunk;
for await (const chunk of child.stderr) stderr += chunk;
const exitCode = await new Promise((r) => child.on("close", r));
if (exitCode !== 0) console.warn(`npm exitCode ${exitCode}`);
if (stderr) throw new Error(stderr);
} else {
stdout = await execCommand(
`npm ${cmd} ${[...argv, ...this.defaultArgv].join(" ")}`.trimEnd(),
{ cwd: npmRoot, env: this.processEnv },
);
}
// Patch init and query stdout as they contains a string before json
if (this.patch) {
if (json && cmd === "init") stdout = substringAfterChar(stdout, "{");
if (cmd === "query") stdout = substringAfterChar(stdout, "[");
}
return json ? JSON.parse(stdout) : stdout;
}
}
export { Npm };
export default new Npm();