-
-
Save ip413/d4769695d9a18298282b08bbe9f0e87e 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 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 | |
main(); | |
function main() { | |
const usageMsg = 'Usage: ...\n'; | |
// If no STDIN and no arguments | |
if (process.stdin.isTTY && process.argv.length <= 2) { | |
process.stderr.write(usageMsg); | |
process.exit(1); | |
} | |
// If no STDIN but arguments given | |
else if (process.stdin.isTTY && process.argv.length > 2) { | |
handleInput('argument', process.argv[2]); | |
} | |
// read from STDIN | |
else { | |
let data = ''; | |
process.stdin.on('readable', () => { | |
data += process.stdin.read() || ''; | |
}); | |
process.stdin.on('end', () => { | |
handleInput('stdin', data); | |
}); | |
} | |
} | |
function handleInput(type, data) { | |
console.log(type, data); | |
} |
This file contains 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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment