-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
107 lines (84 loc) · 2.02 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
// Expose methods.
exports.use = use;
exports.restore = restore;
exports.flush = flush;
/**
* Store original writes.
*/
var originalWrites = {
stdout: process.stdout.write,
stderr: process.stderr.write,
};
/**
* Data.
*/
var cachedData = {
stdout: [],
stderr: [],
};
/**
* Defaults.
*/
var defaultOpts = {
stdout: true,
stderr: true,
print: false,
};
/**
* Start mocking std output.
*
* @param {object} [options] Options
* @param {boolean} [options.stdout=true] Mock stdout
* @param {boolean} [options.stderr=true] Mock stderr
* @param {boolean} [options.print=false] Also print to std
*/
function use(options = {}) {
options = { ...defaultOpts, ...options };
if (options.stdout) wrapWrite("stdout", options.print);
if (options.stderr) wrapWrite("stderr", options.print);
}
/**
* Wrap write method.
*
* @param {string} std Std
* @param {boolean} print Also print to std
*/
function wrapWrite(std, print) {
process[std].write = function (data) {
cachedData[std].push(data);
if (print) originalWrites[std].apply(process[std], arguments);
};
}
/**
* Restore std output.
*
* @param {object} [options] Options
* @param {boolean} [options.stdout=true] Mock stdout
* @param {boolean} [options.stderr=true] Mock stderr
*/
function restore(options = {}) {
options = { ...defaultOpts, ...options };
if (options.stdout) process.stdout.write = originalWrites.stdout;
if (options.stderr) process.stderr.write = originalWrites.stderr;
}
/**
* Flush collected data.
*
* @param {object} [options] Options
* @param {boolean} [options.stdout=true] Mock stdout
* @param {boolean} [options.stderr=true] Mock stderr
* @returns {object} Object containing two array corresponding to outputs.
*/
function flush(options = {}) {
options = { ...defaultOpts, ...options };
var flushed = {};
if (options.stdout) {
flushed.stdout = cachedData.stdout;
cachedData.stdout = [];
}
if (options.stderr) {
flushed.stderr = cachedData.stderr;
cachedData.stderr = [];
}
return flushed;
}