cli (2092B)
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 cwd = require( 'process' ).cwd; // Note: avoiding `@stdlib/process/cwd` is intentional in order to avoid a circular dependency at the package level 27 var CLI = require( '@stdlib/cli/ctor' ); 28 var readFile = require( './../lib' ); 29 30 31 // MAIN // 32 33 /** 34 * Main execution sequence. 35 * 36 * @private 37 * @returns {void} 38 */ 39 function main() { 40 var fpath; 41 var flags; 42 var args; 43 var opts; 44 var cli; 45 46 // Create a command-line interface: 47 cli = new CLI({ 48 'pkg': require( './../package.json' ), 49 'options': require( './../etc/cli_opts.json' ), 50 'help': readFile.sync( resolve( __dirname, '..', 'docs', 'usage.txt' ), { 51 'encoding': 'utf8' 52 }) 53 }); 54 55 // Get any provided command-line options: 56 flags = cli.flags(); 57 if ( flags.help || flags.version ) { 58 return; 59 } 60 61 // Get any provided command-line arguments: 62 args = cli.args(); 63 64 opts = {}; 65 if ( flags.encoding ) { 66 opts.encoding = flags.encoding; 67 } 68 if ( flags.flag ) { 69 opts.flag = flags.flag; 70 } 71 72 fpath = resolve( cwd(), args[ 0 ] ); 73 readFile( fpath, opts, onFile ); 74 75 /** 76 * Callback invoked upon reading the contents of a file. 77 * 78 * @private 79 * @param {(Error|null)} error - error object 80 * @param {(Buffer|string)} file - file contents 81 * @returns {void} 82 */ 83 function onFile( error, file ) { 84 if ( error ) { 85 return cli.error( error ); 86 } 87 console.log( file.toString() ); // eslint-disable-line no-console 88 } 89 } 90 91 main();