bin.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. #!/usr/bin/env node
  2. var Notification = require('./').Notification;
  3. var minimist = require('minimist');
  4. var usage = require('cli-usage');
  5. var aliases = {
  6. 'help': 'h',
  7. 'title': 't',
  8. 'subtitle': 'st',
  9. 'message': 'm',
  10. 'icon': 'i',
  11. 'sound': 's',
  12. 'open': 'o',
  13. 'port': 'p',
  14. };
  15. var argv = minimist(process.argv.slice(2), {
  16. alias: aliases,
  17. string: ['icon', 'message', 'open', 'subtitle', 'title', 'host', 'port']
  18. });
  19. readme(aliases, ['host']);
  20. var validOpts = Object.keys(aliases).concat('host');
  21. var passedOptions = getOptionsIfExists(validOpts, argv);
  22. var stdinMessage = '';
  23. if (process.stdin.isTTY) {
  24. doNotification(passedOptions);
  25. } else {
  26. process.stdin.resume();
  27. process.stdin.setEncoding('utf8');
  28. process.stdin.on('data', function(data) {
  29. if (data) {
  30. stdinMessage += data;
  31. } else {
  32. doNotification(passedOptions);
  33. this.end();
  34. return;
  35. }
  36. });
  37. process.stdin.on('end', function(){
  38. if (stdinMessage) {
  39. passedOptions.message = stdinMessage;
  40. }
  41. doNotification(passedOptions);
  42. });
  43. }
  44. function doNotification (options) {
  45. var notifier = new Notification(options);
  46. if (!options.message) {
  47. // Do not show an empty message
  48. process.exit(0);
  49. }
  50. notifier.notify(options, function (err, msg) {
  51. if (err) {
  52. console.error(err.message);
  53. process.exit(1);
  54. }
  55. if (!msg) return;
  56. console.log(msg);
  57. process.exit(0);
  58. });
  59. }
  60. function getOptionsIfExists(optionTypes, argv) {
  61. var options = {};
  62. optionTypes.forEach(function (key) {
  63. if (key && argv[key]) {
  64. options[key] = argv[key];
  65. }
  66. });
  67. return options;
  68. }
  69. function readme(input, extra) {
  70. var str = '# notify\n \n## Options\n' + params(input, extra) + '\n\n';
  71. str += '## Example\n```shell\n';
  72. str += '$ notify -t "Hello" -m "My Message" -s --open http://github.com\n';
  73. str += '$ notify -t "Agent Coulson" --icon https://raw.githubusercontent.com/mikaelbr/node-notifier/master/example/coulson.jpg \n';
  74. str += '$ notify -m "My Message" -s Glass\n';
  75. str += '$ echo "My Message" | notify -t "Hello"```\n\n';
  76. usage(str);
  77. }
  78. function params(input, extra) {
  79. var withAlias = Object.keys(input).reduce(function (acc, key) {
  80. return acc + ' * --' + key + ' (alias -' + input[key] + ')\n';
  81. }, '');
  82. if (!extra) return withAlias;
  83. return withAlias + extra.reduce(function (acc, key) {
  84. return acc + ' * --' + key + '\n';
  85. }, '')
  86. }