Skip to content

Commit 10465d7

Browse files
committed
Add CLI snippet which supports reading from stdin
1 parent 2995191 commit 10465d7

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed

tools/snippets/bin/cli_stdin

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
#!/usr/bin/env node
2+
'use strict';
3+
4+
// MODULES //
5+
6+
var resolve = require( 'path' ).resolve;
7+
var readFileSync = require( '@stdlib/fs/read-file' ).sync;
8+
var CLI = require( '@stdlib/tools/cli' );
9+
var stdin = require( '@stdlib/utils/read-stdin' );
10+
var RE_EOL = require( '@stdlib/regexp/eol' );
11+
var reFromString = require( '@stdlib/utils/regexp-from-string' );
12+
var TODO = require( './../lib' );
13+
14+
15+
// MAIN //
16+
17+
/**
18+
* Main execution sequence.
19+
*
20+
* @private
21+
* @returns {void}
22+
*/
23+
function main() {
24+
var flags;
25+
var args;
26+
var opts;
27+
var cli;
28+
29+
// Create a command-line interface:
30+
cli = new CLI({
31+
'pkg': require( './../package.json' ),
32+
'options': require( './../etc/cli_opts.json' ),
33+
'help': readFileSync( resolve( __dirname, '..', 'docs', 'usage.txt' ), {
34+
'encoding': 'utf8'
35+
})
36+
});
37+
38+
// Get any provided command-line arguments:
39+
args = cli.args();
40+
41+
// Get any provided command-line flags:
42+
flags = cli.flags();
43+
44+
// Check if we are receiving data from `stdin`...
45+
opts = {};
46+
if ( !process.stdin.isTTY ) {
47+
if ( flags.split ) {
48+
opts.split = reFromString( flags.split );
49+
} else {
50+
opts.split = RE_EOL;
51+
}
52+
return stdin( onRead );
53+
}
54+
console.log( TODO( args[ 0 ] ) ); // eslint-disable-line no-console
55+
56+
/**
57+
* Callback invoked upon reading from `stdin`.
58+
*
59+
* @private
60+
* @param {(Error|null)} error - error object
61+
* @param {Buffer} data - data
62+
* @returns {void}
63+
*/
64+
function onRead( error, data ) {
65+
/* eslint-disable no-console */
66+
var lines;
67+
var i;
68+
if ( error ) {
69+
process.exitCode = 1;
70+
return console.error( 'Error: %s', error.message );
71+
}
72+
lines = data.toString().split( opts.split );
73+
for ( i = 0; i < lines.length; i++ ) {
74+
console.log( TODO( lines[ i ] ) );
75+
}
76+
} // end FUNCTION onRead()
77+
} // end FUNCTION main()
78+
79+
main();

0 commit comments

Comments
 (0)