Last active
March 12, 2024 18:10
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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(); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ echo bob | node read_arguments.js | |
BOB | |
$ node read_arguments.js bob | |
BOB | |
$ node read_arguments.js | |
Usage: filename <input> |
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 forapp.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
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 forapp.js
)