UNPKG

1.31 kBJavaScriptView Raw
1"use strict";
2
3/**
4 * Module dependencies.
5 */
6
7var _ = require("lodash");
8
9/**
10 * Intercepts stdout, passes thru callback
11 * also pass console.error thru stdout so it goes to callback too
12 * (stdout.write and stderr.write are both refs to the same stream.write function)
13 * returns an unhook() function, call when done intercepting
14 *
15 * @param {Function} callback
16 * @return {Function}
17 */
18
19module.exports = function (callback) {
20
21 var oldStdoutWrite = process.stdout.write,
22 oldConsoleError = console.error;
23
24 process.stdout.write = (function(write) {
25 return function(string) {
26 var args = _.toArray(arguments);
27 args[0] = interceptor( string );
28 write.apply(process.stdout, args);
29 };
30 }(process.stdout.write));
31
32 console.error = (function() {
33 return function() {
34 var args = _.toArray(arguments);
35 args.unshift("\x1b[31m[ERROR]\x1b[0m");
36 console.log.apply(console.log, args);
37 };
38 }(console.error));
39
40 function interceptor(string) {
41 // only intercept the string
42 var result = callback(string);
43 if (typeof result === "string") {
44 string = result.replace( /\n$/, "" ) + (result && (/\n$/).test( string ) ? "\n" : "");
45 }
46 return string;
47 }
48
49 // puts back to original
50 return function unhook() {
51 process.stdout.write = oldStdoutWrite;
52 console.error = oldConsoleError;
53 };
54
55};