-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathintercept-stdout.js
53 lines (44 loc) · 1.48 KB
/
intercept-stdout.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
// Borrowed.
// https://gist.github.com/benbuckman/2758563
var toArray = require('lodash.toarray'),
util = require('util');
// Intercept stdout and stderr to pass output thru callback.
//
// Optionally, takes two callbacks.
// If two callbacks are specified,
// the first intercepts stdout, and
// the second intercepts stderr.
//
// returns an unhook() function, call when done intercepting
module.exports = function (stdoutIntercept, stderrIntercept) {
stderrIntercept = stderrIntercept || stdoutIntercept;
var old_stdout_write = process.stdout.write;
var old_stderr_write = process.stderr.write;
process.stdout.write = (function(write) {
return function(string, encoding, fd) {
var args = toArray(arguments);
args[0] = interceptor( string, stdoutIntercept );
write.apply(process.stdout, args);
};
}(process.stdout.write));
process.stderr.write = (function(write) {
return function(string, encoding, fd) {
var args = toArray(arguments);
args[0] = interceptor( string, stderrIntercept );
write.apply(process.stderr, args);
};
}(process.stderr.write));
function interceptor(string, callback) {
// only intercept the string
var result = callback(string);
if (typeof result == 'string') {
string = result.replace( /\n$/ , '' ) + (result && (/\n$/).test( string ) ? '\n' : '');
}
return string;
}
// puts back to original
return function unhook() {
process.stdout.write = old_stdout_write;
process.stderr.write = old_stderr_write;
};
};