cli (2388B)
1 #!/usr/bin/env node 2 3 /** 4 * @license Apache-2.0 5 * 6 * Copyright (c) 2018 The Stdlib Authors. 7 * 8 * Licensed under the Apache License, Version 2.0 (the "License"); 9 * you may not use this file except in compliance with the License. 10 * You may obtain a copy of the License at 11 * 12 * http://www.apache.org/licenses/LICENSE-2.0 13 * 14 * Unless required by applicable law or agreed to in writing, software 15 * distributed under the License is distributed on an "AS IS" BASIS, 16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 * See the License for the specific language governing permissions and 18 * limitations under the License. 19 */ 20 21 'use strict'; 22 23 // MODULES // 24 25 var resolve = require( 'path' ).resolve; 26 var readFileSync = require( '@stdlib/fs/read-file' ).sync; 27 var CLI = require( '@stdlib/cli/ctor' ); 28 var stdout = require( '@stdlib/streams/node/stdout' ); 29 var constantStream = require( './../lib' ); 30 31 32 // FUNCTIONS // 33 34 /** 35 * Callback invoked once a source stream ends. 36 * 37 * @private 38 */ 39 function onEnd() { 40 // Append a trailing newline in accordance with standard POSIX behavior: 41 console.log( '' ); // eslint-disable-line no-console 42 } 43 44 45 // MAIN // 46 47 /** 48 * Main execution sequence. 49 * 50 * @private 51 * @returns {void} 52 */ 53 function main() { 54 var stream; 55 var flags; 56 var opts; 57 var args; 58 var cli; 59 var err; 60 61 // Create a command-line interface: 62 cli = new CLI({ 63 'pkg': require( './../package.json' ), 64 'options': require( './../etc/cli_opts.json' ), 65 'help': readFileSync( resolve( __dirname, '..', 'docs', 'usage.txt' ), { 66 'encoding': 'utf8' 67 }) 68 }); 69 70 // Get any provided command-line options: 71 flags = cli.flags(); 72 if ( flags.help || flags.version ) { 73 return; 74 } 75 76 // Get any provided command-line arguments: 77 args = cli.args(); 78 if ( args.length < 1 ) { 79 err = new Error( 'insufficient arguments. Must provide a value to stream.' ); 80 return onError( err ); 81 } 82 83 opts = {}; 84 if ( flags.iter ) { 85 opts.iter = parseInt( flags.iter, 10 ); 86 } 87 if ( flags.sep ) { 88 opts.sep = flags.sep; 89 } 90 91 // Create a source stream and pipe to `stdout`: 92 stream = constantStream( args[ 0 ].toString(), opts ); 93 stream.on( 'end', onEnd ); 94 95 stream.pipe( stdout ); 96 97 /** 98 * Callback invoked upon encountering an error. 99 * 100 * @private 101 * @param {Error} error - error 102 * @param {integer} [code] - exit code 103 */ 104 function onError( error, code ) { 105 cli.error( error, code || 1 ); 106 } 107 } 108 109 main();