11'use strict' ;
22
33const util = require ( 'util' ) ;
4+ const { doNotEmitErrorEvent } = require ( 'stream' ) . Writable ;
45
5- function Console ( stdout , stderr ) {
6+ function Console ( stdout , stderr , ignoreErrors ) {
67 if ( ! ( this instanceof Console ) ) {
7- return new Console ( stdout , stderr ) ;
8+ return new Console ( stdout , stderr , ignoreErrors ) ;
89 }
910 if ( ! stdout || typeof stdout . write !== 'function' ) {
1011 throw new TypeError ( 'Console expects a writable stream instance' ) ;
@@ -24,6 +25,8 @@ function Console(stdout, stderr) {
2425 Object . defineProperty ( this , '_stdout' , prop ) ;
2526 prop . value = stderr ;
2627 Object . defineProperty ( this , '_stderr' , prop ) ;
28+ prop . value = ignoreErrors === undefined ? true : ! ! ignoreErrors ;
29+ Object . defineProperty ( this , '_ignoreErrors' , prop ) ;
2730 prop . value = new Map ( ) ;
2831 Object . defineProperty ( this , '_times' , prop ) ;
2932
@@ -35,20 +38,32 @@ function Console(stdout, stderr) {
3538 }
3639}
3740
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+
3853
3954// As of v8 5.0.71.32, the combination of rest param, template string
4055// and .apply(null, args) benchmarks consistently faster than using
4156// the spread operator when calling util.format.
4257Console . 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` ) ;
4459} ;
4560
4661
4762Console . prototype . info = Console . prototype . log ;
4863
4964
5065Console . 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` ) ;
5267} ;
5368
5469
@@ -57,7 +72,7 @@ Console.prototype.error = Console.prototype.warn;
5772
5873Console . prototype . dir = function dir ( object , options ) {
5974 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` ) ;
6176} ;
6277
6378
0 commit comments