'use strict';

// MODULES //

var isFunction = require( '@stdlib/utils/is-function' );
var isString = require( '@stdlib/utils/is-string' ).isPrimitive;
var stream = require( '@stdlib/streams/base/stdin' );


// MAIN //

/**
* Reads data from `stdin`.
*
* @param {(string|null)} [encoding] - string encoding. If set, data will be returned as an encoded `string`.
* @param {Function} clbk - callback to invoked upon reading all data from `stdin`
*
* @example
* function onRead( error, data ) {
*     if ( error ) {
*         throw error;
*     }
*     console.log( data.toString() );
*     // returns '...'
* }
*
* stdin( onRead );
*
* @example
* function onRead( error, data ) {
*     if ( error ) {
*         throw error;
*     }
*     console.log( data );
*     // returns '...'
* }
*
* stdin( 'utf8', onRead );
*/
function stdin() {
	var clbk;
	var data;
	var enc;
	var len;

	if ( arguments.length === 1 ) {
		clbk = arguments[ 0 ];
	} else {
		enc = arguments[ 0 ];
		if ( !isString( enc ) ) {
			throw new TypeError( 'invalid input argument. Encoding argument must be a string. Value: `' + enc + '`.' );
		}
		clbk = arguments[ 1 ];
	}
	if ( !isFunction( clbk ) ) {
		throw new TypeError( 'invalid input argument. Callback argument must be a function. Value: `' + clbk + '`.' );
	}
	if ( enc ) {
		stream.setEncoding( enc );
	}
	// If the calling file is being run as a script and not as part of a pipeline, we should not expect to receive anything on `stdin`.
	if ( stream.isTTY ) {
		return process.nextTick( nextTick );
	}
	data = [];
	len = 0;

	stream.on( 'readable', onReadable );
	stream.on( 'error', onError );
	stream.on( 'end', onEnd );

	/**
	* Callback invoked after the next tick.
	*
	* @private
	*/
	function nextTick() {
		if ( enc ) {
			return clbk( null, '' );
		}
		clbk( null, new Buffer( '' ) );
	} // end FUNCTION nextTick()

	/**
	* Callback invoked once the stream has data to consume.
	*
	* @private
	*/
	function onReadable() {
		var chunk;
		while ( true ) {
			chunk = stream.read();
			if ( chunk === null ) {
				break;
			}
			data.push( chunk );
			len += chunk.length;
		}
	} // end FUNCTION onReadable()

	/**
	* Callback invoked upon encountering a stream error.
	*
	* @private
	* @param {Error} error - error object
	*/
	function onError( error ) {
		clbk( error );
	} // end FUNCTION onError()

	/**
	* Callback invoked after all data has been consumed.
	*
	* @private
	*/
	function onEnd() {
		if ( enc ) {
			// Return a string...
			return clbk( null, data.join( '' ) );
		}
		// Return a buffer...
		clbk( null, Buffer.concat( data, len ) );
	} // end FUNCTION onEnd()
} // end FUNCTION stdin()


// EXPORTS //

module.exports = stdin;

@@ -437,16 +437,34 @@
 %60stdin%60%0A
+* @returns %7Bvoid%7D%0A
 *%0A* @exa
@@ -1717,32 +1717,51 @@
 %0A%09*%0A%09* @private%0A
+%09* @returns %7Bvoid%7D%0A
 %09*/%0A%09function ne
@@ -2433,32 +2433,51 @@
 %0A%09*%0A%09* @private%0A
+%09* @returns %7Bvoid%7D%0A
 %09*/%0A%09function on

Fix lint errors