github.com/emc-advanced-dev/unik@v0.0.0-20190717152701-a58d3e8e33b7/containers/compilers/rump/nodejs/node-wrapper/fixture-stdout.js (about)

     1  /**
     2   * Module Dependencies
     3   */
     4  var util = require('util');
     5  var Stream = require('stream');
     6  
     7  
     8  /**
     9   * Test fixture which globally intercepts writes
    10   * to stdout.
    11   *
    12   * Based on: https://gist.github.com/pguillory/729616
    13   *
    14   * @option {Stream}				[stream to intercept to-- defaults to stdout]
    15   *
    16   * @return {Function}          [an instance of the fixture]
    17   */
    18  
    19  var StdOutFixture = function ( options ) {
    20  
    21  	// Options
    22  	if ( typeof options !== 'object' ) options = {};
    23  	if ( options instanceof Stream ) options = { stream: options };
    24  	var stream = options.stream || process.stdout;
    25  
    26  	// Replace stdout
    27  	var _intercept = function (callback) {
    28  		var original_stdout_write = stream.write;
    29  
    30  		stream.write = (function (write) {
    31  			return function (string, encoding, fd) {
    32  				var interceptorReturnedFalse = false === callback(string, encoding, fd);
    33  				if (interceptorReturnedFalse) return;
    34  				else write.apply(stream, arguments);
    35  			};
    36  		})(stream.write);
    37  
    38  		return function _revert () {
    39  			stream.write = original_stdout_write;
    40  		};
    41  	};
    42  
    43  	// Revert to the original stdout
    44  	var _release;
    45  
    46  
    47  	/**
    48  	 * [Capture writes sent to stdout]
    49  	 * @param  {[type]} interceptFn [run each time a write is intercepted]
    50  	 */
    51  	this.capture = function (interceptFn) {
    52  
    53  		// Default interceptFn
    54  		interceptFn = interceptFn || function (string, encoding, fd) {
    55  			util.debug('(intercepted a write to stdout) ::\n' + util.inspect(string));
    56  		};
    57  
    58  		// Save private `release` method for use later.
    59  		_release = _intercept(interceptFn);
    60  	};
    61  
    62  	/**
    63  	 * Stop capturing writes to stdout
    64  	 */
    65  	this.release = function () {
    66  		_release();
    67  	};
    68  };
    69  
    70  
    71  
    72  // Export the constructor
    73  module.exports = StdOutFixture;