Skip to content

Instantly share code, notes, and snippets.

@khoazero123
Forked from ishu3101/read_arguments.js
Created April 24, 2020 03:27
Show Gist options
  • Select an option

  • Save khoazero123/535036c4da20e1876b4ed3ab0c406248 to your computer and use it in GitHub Desktop.

Select an option

Save khoazero123/535036c4da20e1876b4ed3ab0c406248 to your computer and use it in GitHub Desktop.
Accept input via stdin and arguments in a command line application in node.js
#!/usr/bin/env node
var args = process.argv.slice(2);
var input = args[0];
var isTTY = process.stdin.isTTY;
var stdin = process.stdin;
var stdout = process.stdout;
// If no STDIN and no arguments, display usage message
if (isTTY && args.length === 0) {
console.log("Usage: ");
}
// If no STDIN but arguments given
else if (isTTY && args.length !== 0) {
handleShellArguments();
}
// read from STDIN
else {
handlePipedContent();
}
function handlePipedContent() {
var data = '';
stdin.on('readable', function() {
var chuck = stdin.read();
if(chuck !== null){
data += chuck;
}
});
stdin.on('end', function() {
stdout.write(uppercase(data));
});
}
function handleShellArguments(){
console.log(uppercase(input));
}
function uppercase(data){
return data.toUpperCase();
}
$ echo bob | node read_arguments.js
BOB
$ node read_arguments.js bob
BOB
$ node read_arguments.js
Usage: filename <input>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment