-
Notifications
You must be signed in to change notification settings - Fork 9
/
stream-spy.js
50 lines (42 loc) · 1 KB
/
stream-spy.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
/**
* Hooking into Node.js stdout
* Based on: https://gist.github.com/pguillory/729616 by @pguillory
*
* @param {Object} callback
*/
function hook_stream(stream, callback) {
var old_write = stream.write;
stream.write = (function(write) {
return function(string, encoding, fd) {
write.apply(stream, arguments);
callback(string, encoding, fd);
};
})(stream.write);
return function() {
stream.write = old_write;
};
};
module.exports.lastCharacter = '\n';
function getLastCharacter(string, encoding, fd){
module.exports.lastCharacter = string.slice(-1);
}
var unhook;
var unhookStderr;
module.exports.enable = function enable(){
if(!unhook){
unhook = hook_stream(process.stdout, getLastCharacter);
}
if(!unhookStderr){
unhookStderr = hook_stream(process.stderr, getLastCharacter);
}
};
module.exports.disable = function disable(){
if(unhook){
unhook();
unhook = undefined;
}
if(unhookStderr){
unhookStderr();
unhookStderr = undefined;
}
};