Skip to content

Instantly share code, notes, and snippets.

@ishu3101
Last active March 12, 2024 18:10
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save ishu3101/9fa58ca1440f780d6288 to your computer and use it in GitHub Desktop.
Save ishu3101/9fa58ca1440f780d6288 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>
@Philam18
Copy link

What about both input from the command line as well as piped input?
(e.g. $ echo bob | node app.js -f, where -f is some optional parameter for app.js)

@theoparis
Copy link

What about both input from the command line as well as piped input?
(e.g. $ echo bob | node app.js -f, where -f is some optional parameter for app.js)

Yeah, how would I do this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment