README.md (2481B)
1 <!-- 2 3 @license Apache-2.0 4 5 Copyright (c) 2018 The Stdlib Authors. 6 7 Licensed under the Apache License, Version 2.0 (the "License"); 8 you may not use this file except in compliance with the License. 9 You may obtain a copy of the License at 10 11 http://www.apache.org/licenses/LICENSE-2.0 12 13 Unless required by applicable law or agreed to in writing, software 14 distributed under the License is distributed on an "AS IS" BASIS, 15 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 See the License for the specific language governing permissions and 17 limitations under the License. 18 19 --> 20 21 # Standard Input 22 23 > [Standard input][standard-streams]. 24 25 <section class="usage"> 26 27 ## Usage 28 29 ```javascript 30 var stdin = require( '@stdlib/streams/node/stdin' ); 31 ``` 32 33 #### stdin 34 35 [Standard input][standard-streams] as a [Readable stream][readable-stream]. 36 37 <!-- run-disable --> 38 39 ```javascript 40 var string2buffer = require( '@stdlib/buffer/from-string' ); 41 var Buffer = require( '@stdlib/buffer/ctor' ); 42 43 var data = []; 44 var len = 0; 45 46 stdin.on( 'readable', onReadable ); 47 stdin.on( 'error', onError ); 48 stdin.on( 'end', onEnd ); 49 50 function onReadable() { 51 var chunk; 52 while ( true ) { 53 chunk = stdin.read(); 54 if ( chunk === null ) { 55 break; 56 } 57 if ( typeof chunk === 'string' ) { 58 chunk = string2buffer( chunk ); 59 } 60 data.push( chunk ); 61 len += chunk.length; 62 } 63 } 64 65 function onError( error ) { 66 if ( error ) { 67 console.error( error.message ); 68 } 69 } 70 71 function onEnd() { 72 data = Buffer.concat( data, len ); 73 console.log( data.toString() ); 74 // => '...' 75 } 76 ``` 77 78 </section> 79 80 <!-- /.usage --> 81 82 <section class="examples"> 83 84 ## Examples 85 86 <!-- run-disable --> 87 88 <!-- eslint no-undef: "error" --> 89 90 ```javascript 91 var proc = require( 'process' ); 92 var stdin = require( '@stdlib/streams/node/stdin' ); 93 var stdout = require( '@stdlib/streams/node/stdout' ); 94 95 // Set the encoding: 96 stdin.setEncoding( 'utf8' ); 97 98 // Create an echo stream: 99 stdin.pipe( stdout ); 100 101 // Push data to `stdin`: 102 stdin.push( 'beep' ); 103 stdin.push( ' ' ); 104 stdin.push( 'boop' ); 105 stdin.push( '\n' ); 106 107 // End the stream: 108 stdin.push( null ); 109 110 // Ensure the process closes: 111 setTimeout( proc.exit, 1000 ); 112 ``` 113 114 </section> 115 116 <!-- /.examples --> 117 118 <section class="links"> 119 120 [standard-streams]: https://en.wikipedia.org/wiki/Standard_streams 121 122 [readable-stream]: https://nodejs.org/api/stream.html#stream_class_stream_readable 123 124 </section> 125 126 <!-- /.links -->