Skip to content

Instantly share code, notes, and snippets.

@ip413
Forked from ishu3101/read_arguments.js
Last active May 29, 2021 17:13
Show Gist options
  • Save ip413/d4769695d9a18298282b08bbe9f0e87e to your computer and use it in GitHub Desktop.
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
#!/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);
}
$ 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