-
Notifications
You must be signed in to change notification settings - Fork 278
/
intercept.js
executable file
·51 lines (45 loc) · 1.32 KB
/
intercept.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
'use strict';
/**
* Module dependencies.
*/
var _ = require('lodash');
/**
* Intercepts stdout, passes thru callback
* also pass console.error thru stdout so it goes to callback too
* (stdout.write and stderr.write are both refs to the same stream.write function)
* returns an unhook() function, call when done intercepting
*
* @param {Function} callback
* @return {Function}
*/
module.exports = function (callback) {
var oldStdoutWrite = process.stdout.write;
var oldConsoleError = console.error;
process.stdout.write = function (write) {
return function (string) {
var args = _.toArray(arguments);
args[0] = interceptor(string);
write.apply(process.stdout, args);
};
}(process.stdout.write);
console.error = function () {
return function () {
var args = _.toArray(arguments);
args.unshift('\x1b[31m[ERROR]\x1b[0m');
console.log.apply(console.log, args);
};
}(console.error);
function interceptor(string) {
// 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 = oldStdoutWrite;
console.error = oldConsoleError;
};
};