Skip to content

Instantly share code, notes, and snippets.

@remino
Last active March 24, 2020 07:45
Show Gist options
  • Save remino/2222b326c9880085a38cb4158223230c to your computer and use it in GitHub Desktop.
Save remino/2222b326c9880085a38cb4158223230c to your computer and use it in GitHub Desktop.
New Node script using babel-node
#!/usr/bin/env npx babel-node --
// vim: ft=javascript
const readline = require('readline');
const minimist = require('minimist');
const { basename } = require('path');
const errors = {
general: 1,
missingArg: 16,
};
class ConsoleError extends Error {
constructor(code = errors.general, ...params) {
super(...params);
this.name = 'ConsoleError';
this.code = code;
}
}
const help = () => {
console.log(`
Usage: ${basename(process.argv[1])} [options] [words]
Ask a question.
Options:
-h, --help Show this help screen.
`);
};
process.on('uncaughtException', (e) => {
console.error(e);
if (e.code === errors.missingArg) help();
process.exit(e.code || errors.general);
});
process.on('unhandledRejection', (e) => { throw e; });
const opts = argv => minimist(argv, {
alias: {
h: 'help',
},
boolean: ['h'],
default: {
h: false,
},
});
const question = (prompt) => {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
return new Promise((resolve) => {
rl.question(prompt, (r) => {
rl.close();
resolve(r);
});
});
};
const ask = async (...words) => {
if (words.length < 1) {
throw new ConsoleError(errors.missingArg, 'Question needs words.');
}
const response = await question(`${words.join(' ')} `);
console.log(response);
return response;
};
const controller = async (args) => {
switch (true) {
case args.h: return help();
default: return ask(...args._);
}
};
const main = argv => new Promise(async (resolve) => {
await controller(opts(argv));
return resolve(0);
});
main(process.argv.slice(2))
.then(() => { process.exit(); })
.catch((e) => { throw e; });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment