UNPKG

1.54 kBJavaScriptView Raw
1const cp = require('child_process');
2const _ = require('lodash');
3
4function execSync(command) {
5 const normalized = normalizeSpace(command);
6 console.log(normalized);
7 cp.execSync(normalized, { stdio: ['inherit', 'inherit', 'inherit'] });
8}
9
10function execSyncSilent(command) {
11 const normalized = normalizeSpace(command);
12 cp.execSync(normalized, { stdio: ['ignore', 'ignore', 'ignore'] });
13}
14
15function execSyncRead(command) {
16 const normalized = normalizeSpace(command);
17 console.log(normalized);
18 return _.trim(String(cp.execSync(normalized, { stdio: ['inherit', 'pipe', 'inherit'] })));
19}
20
21function execAsync(command) {
22 const normalized = normalizeSpace(command);
23 return new Promise((resolve, reject) => {
24 const child = cp.exec(normalized, (err, stdout, stderr) => {
25 if (err) {
26 reject(err);
27 } else {
28 resolve({ stdout, stderr });
29 }
30 });
31 child.stdout.pipe(process.stdout);
32 child.stderr.pipe(process.stderr);
33 });
34}
35
36function kill(process) {
37 execSyncSilent(`pkill -f "${process}" || true`);
38}
39
40function killPort(port) {
41 execSync(`lsof -t -i :${port} | xargs kill || true`);
42}
43
44function which(what) {
45 try {
46 return execSyncRead(`which ${what}`);
47 } catch (e) {
48 return undefined;
49 }
50}
51
52module.exports = {
53 execSync,
54 execSyncSilent,
55 execSyncRead,
56 execAsync,
57 kill,
58 which,
59 killPort
60};
61
62const WHITESPACE_REGEX = /\s+/g;
63
64function normalizeSpace(str) {
65 if (!_.isString(str)) {
66 return '';
67 }
68 return _.replace(_.trim(str), WHITESPACE_REGEX, ' ');
69}
70