-
Notifications
You must be signed in to change notification settings - Fork 16
/
index.js
87 lines (76 loc) · 1.94 KB
/
index.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/*============================================================================
* Copyright(c) 2010 Mario L Gutierrez <[email protected]>
* MIT Licensed
*==========================================================================*/
var temp = require('temp');
var fs = require('fs');
var isWindows = require('os').platform().indexOf('win') === 0;
var shell;
if (isWindows) {
if (!fs.existsSync(__dirname + '/build/Release/shell.node')) {
var nodeVersion = process.version;
var shellLib = 'v0.8/shell';
if (nodeVersion.indexOf('v0.10') === 0)
shellLib = 'v0.10/shell';
try {
//! Loading an add-on built for another version of nodeJs may
//! cause seg faults. Windows + open source is not always pleasant
shell = require('./win32/' + shellLib);
} catch (err) {
console.error(err);
throw new Error('execSync incompatible with installed nodejs');
}
}
}
if (!shell) {
shell = require('./build/Release/shell');
}
/**
* Runs `cmd` synchronously returning the exit code.
*/
function run(cmd) {
try {
if (isWindows)
cmd = 'cmd /C ' + cmd;
var code = shell.exec(cmd);
return code;
} catch (err) {
if (err) {
console.error(err)
}
return 1;
}
}
/**
* Executes `command` synchronously capturing the output.
*
* This is a wrapper around `run` function.
*/
function exec(command) {
var tempName = temp.path({suffix: '.exec'});
var cmd;
if (isWindows)
cmd = command + ' > ' + tempName + ' 2>&1';
else
cmd = '(' + command + ') > ' + tempName + ' 2>&1';
var code = run(cmd);
var text;
if (fs.existsSync(tempName)) {
try {
text = fs.readFileSync(tempName, 'utf8');
fs.unlink(tempName);
} catch (err) {
throw new Error('ERROR: could not delete capture file');
}
} else {
throw new Error('ERROR: output not captured');
}
return {
code: code,
stdout: text
}
}
module.exports = {
run: run,
exec: exec
};