stdin

Read data from stdin.

Usage

var stdin = require( '@stdlib/process/read-stdin' );

stdin( [encoding,] clbk )

Reads data from stdin.

function onRead( error, data ) {
    if ( error ) {
        throw error;
    }
    console.log( data.toString() );
    // returns '...'
}

stdin( onRead );

By default, returned data is a Buffer. To return a string of a specified encoding, provide an encoding parameter.

function onRead( error, data ) {
    if ( error ) {
        throw error;
    }
    console.log( data );
    // returns '...'
}

stdin( 'utf8', onRead );

When a file's calling Node.js process is running in a TTY context (i.e., no stdin), data will either be an empty Buffer (no encoding provided) or an empty string (encoding provided).

function onRead( error, data ) {
    if ( error ) {
        throw error;
    }
    console.log( data );
    // returns ''
}

process.stdin.isTTY = true;

stdin( 'utf8', onRead );

Examples

var string2buffer = require( '@stdlib/buffer/from-string' );
var stdin = require( '@stdlib/process/read-stdin' );

function onRead( error, data ) {
    if ( error ) {
        throw error;
    }
    console.log( data.toString() );
    // returns 'beep boop'
}

// Fake not being in a terminal context:
process.stdin.isTTY = false;

// Provide a callback to consume all data from `stdin`:
stdin( onRead );

// Push some data to `stdin`:
process.stdin.push( string2buffer( 'beep' ) );
process.stdin.push( string2buffer( ' ' ) );
process.stdin.push( string2buffer( 'boop' ) );

// End the stream:
process.stdin.push( null );