1
1
'use strict' ;
2
2
3
3
const util = require ( 'util' ) ;
4
+ const { doNotEmitErrorEvent } = require ( 'stream' ) . Writable ;
4
5
5
- function Console ( stdout , stderr ) {
6
+ function Console ( stdout , stderr , ignoreErrors ) {
6
7
if ( ! ( this instanceof Console ) ) {
7
- return new Console ( stdout , stderr ) ;
8
+ return new Console ( stdout , stderr , ignoreErrors ) ;
8
9
}
9
10
if ( ! stdout || typeof stdout . write !== 'function' ) {
10
11
throw new TypeError ( 'Console expects a writable stream instance' ) ;
@@ -24,6 +25,8 @@ function Console(stdout, stderr) {
24
25
Object . defineProperty ( this , '_stdout' , prop ) ;
25
26
prop . value = stderr ;
26
27
Object . defineProperty ( this , '_stderr' , prop ) ;
28
+ prop . value = ignoreErrors === undefined ? true : ! ! ignoreErrors ;
29
+ Object . defineProperty ( this , '_ignoreErrors' , prop ) ;
27
30
prop . value = new Map ( ) ;
28
31
Object . defineProperty ( this , '_times' , prop ) ;
29
32
@@ -35,20 +38,32 @@ function Console(stdout, stderr) {
35
38
}
36
39
}
37
40
41
+ function write ( ignoreErrors , stream , string ) {
42
+ if ( ! ignoreErrors ) return stream . write ( string ) ;
43
+
44
+ try {
45
+ stream . write ( string , ( err ) => {
46
+ return doNotEmitErrorEvent ;
47
+ } ) ;
48
+ } catch ( e ) {
49
+ // Sorry, there’s proper way to pass along the error here.
50
+ }
51
+ }
52
+
38
53
39
54
// As of v8 5.0.71.32, the combination of rest param, template string
40
55
// and .apply(null, args) benchmarks consistently faster than using
41
56
// the spread operator when calling util.format.
42
57
Console . prototype . log = function log ( ...args ) {
43
- this . _stdout . write ( `${ util . format . apply ( null , args ) } \n` ) ;
58
+ write ( this . _ignoreErrors , this . _stdout , `${ util . format . apply ( null , args ) } \n` ) ;
44
59
} ;
45
60
46
61
47
62
Console . prototype . info = Console . prototype . log ;
48
63
49
64
50
65
Console . prototype . warn = function warn ( ...args ) {
51
- this . _stderr . write ( `${ util . format . apply ( null , args ) } \n` ) ;
66
+ write ( this . _ignoreErrors , this . _stderr , `${ util . format . apply ( null , args ) } \n` ) ;
52
67
} ;
53
68
54
69
@@ -57,7 +72,7 @@ Console.prototype.error = Console.prototype.warn;
57
72
58
73
Console . prototype . dir = function dir ( object , options ) {
59
74
options = Object . assign ( { customInspect : false } , options ) ;
60
- this . _stdout . write ( `${ util . inspect ( object , options ) } \n` ) ;
75
+ write ( this . _ignoreErrors , this . _stdout , `${ util . inspect ( object , options ) } \n` ) ;
61
76
} ;
62
77
63
78
0 commit comments