-
-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathindex.js
75 lines (56 loc) · 1.68 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
import process from 'node:process';
import {Buffer} from 'node:buffer';
const hook = (stream, options, transform) => {
if (typeof options !== 'object') {
transform = options;
options = {};
}
options = {
silent: true,
once: false,
...options,
};
let unhookFunction;
const promise = new Promise(resolve => {
const {write} = stream;
const unhook = () => {
stream.write = write;
resolve();
};
stream.write = (output, encoding, callback) => {
const callbackReturnValue = transform(String(output), unhook);
if (options.once) {
unhook();
}
if (options.silent) {
return typeof callbackReturnValue === 'boolean' ? callbackReturnValue : true;
}
let returnValue;
if (typeof callbackReturnValue === 'string') {
returnValue = typeof encoding === 'string' ? Buffer.from(callbackReturnValue).toString(encoding) : callbackReturnValue;
}
returnValue = returnValue || (Buffer.isBuffer(callbackReturnValue) ? callbackReturnValue : output);
return write.call(stream, returnValue, encoding, callback);
};
unhookFunction = unhook;
});
promise.unhook = unhookFunction;
return promise;
};
export function hookStd(options, transform) {
const streams = options.streams || [process.stdout, process.stderr];
const streamPromises = streams.map(stream => hook(stream, options, transform));
const promise = Promise.all(streamPromises);
promise.unhook = () => {
for (const streamPromise of streamPromises) {
streamPromise.unhook();
}
};
return promise;
}
export function hookStdout(...arguments_) {
return hook(process.stdout, ...arguments_);
}
export function hookStderr(...arguments_) {
return hook(process.stderr, ...arguments_);
}