time-to-botec

Benchmark sampling in different programming languages
Log | Files | Refs | README

destroy.js (1565B)


      1 /**
      2 * @license Apache-2.0
      3 *
      4 * Copyright (c) 2018 The Stdlib Authors.
      5 *
      6 * Licensed under the Apache License, Version 2.0 (the "License");
      7 * you may not use this file except in compliance with the License.
      8 * You may obtain a copy of the License at
      9 *
     10 *    http://www.apache.org/licenses/LICENSE-2.0
     11 *
     12 * Unless required by applicable law or agreed to in writing, software
     13 * distributed under the License is distributed on an "AS IS" BASIS,
     14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     15 * See the License for the specific language governing permissions and
     16 * limitations under the License.
     17 */
     18 
     19 'use strict';
     20 
     21 // MODULES //
     22 
     23 var logger = require( 'debug' );
     24 var nextTick = require( '@stdlib/utils/next-tick' );
     25 
     26 
     27 // VARIABLES //
     28 
     29 var debug = logger( 'transform-stream:destroy' );
     30 
     31 
     32 // MAIN //
     33 
     34 /**
     35 * Gracefully destroys a stream, providing backward compatibility.
     36 *
     37 * @private
     38 * @param {Object} [error] - optional error message
     39 * @returns {Stream} stream instance
     40 */
     41 function destroy( error ) {
     42 	/* eslint-disable no-invalid-this */
     43 	var self;
     44 	if ( this._destroyed ) {
     45 		debug( 'Attempted to destroy an already destroyed stream.' );
     46 		return this;
     47 	}
     48 	self = this;
     49 	this._destroyed = true;
     50 
     51 	nextTick( close );
     52 
     53 	return this;
     54 
     55 	/**
     56 	* Closes a stream.
     57 	*
     58 	* @private
     59 	*/
     60 	function close() {
     61 		if ( error ) {
     62 			debug( 'Stream was destroyed due to an error. Error: %s.', JSON.stringify( error ) );
     63 			self.emit( 'error', error );
     64 		}
     65 		debug( 'Closing the stream...' );
     66 		self.emit( 'close' );
     67 	}
     68 }
     69 
     70 
     71 // EXPORTS //
     72 
     73 module.exports = destroy;