System Notifications with Node.js

By  on  

Node Notifications

Notifications can be a godsend or the bane of our existence these days.  Every app you install on your phone wants access to notifications, as do desktop apps, and now we have a Web Notifications API along with a Web Push API,  just in case you don't already have enough notifications in your life.  Appointment reminders from Calendar are always welcome (I'd otherwise forget every event) but does Wacky Mini Golf really need to notify me that I haven't played in 4 days?  Probably not.

Anyways, I was thinking about notifications and how I could use them to remember stuff I needed to do at a certain time during the current day; i.e. remind myself to go eat lunch, go for a bike ride, or go pick my son up from school on the odd day.  Being a JavaScript nerd I decided to look into creating Mac notifications using Node.js and I quickly found my answer: node-notifier!  Let's take a look!

Create a Simple Notification

node-notifier works on both Mac and Windows PCs.  Notifications can range from very simple to advanced so let's first create a very simple notification:

const notifier = require('node-notifier');

// String
notifier.notify('Go empty the dishwasher!');

// Object
notifier.notify({
  'title': 'David Walsh Blog',
  'subtitle': 'Daily Maintenance',
  'message': 'Go approve comments in moderation!',
  'icon': 'dwb-logo.png',
  'contentImage': 'blog.png',
  'sound': 'ding.mp3',
  'wait': true
});

You can provide notifier the basics like an title, message, and icon, then go further to add a content image, a sound, and even control the buttons that display in the notification.

Advanced Notifications

You can create advanced, feature-rich notifications with node-notifier, including the ability to reply, control the notification button labels, and more.  The following is a more advanced example:

const NotificationCenter = require('node-notifier').NotificationCenter;

var notifier = new NotificationCenter({
  withFallback: false, // Use Growl Fallback if <= 10.8
  customPath: void 0 // Relative/Absolute path to binary if you want to use your own fork of terminal-notifier
});

notifier.notify({
  'title': void 0,
  'subtitle': void 0,
  'message': 'Click "reply" to send a message back!',
  'sound': false, // Case Sensitive string for location of sound file, or use one of macOS' native sounds (see below)
  'icon': 'Terminal Icon', // Absolute Path to Triggering Icon
  'contentImage': void 0, // Absolute Path to Attached Image (Content Image)
  'open': void 0, // URL to open on Click
  'wait': false, // Wait for User Action against Notification or times out. Same as timeout = 5 seconds

  // New in latest version. See `example/macInput.js` for usage
  timeout: 5, // Takes precedence over wait if both are defined.
  closeLabel: void 0, // String. Label for cancel button
  actions: void 0, // String | Array<String>. Action label or list of labels in case of dropdown
  dropdownLabel: void 0, // String. Label to be used if multiple actions
  reply: false // Boolean. If notification should take input. Value passed as third argument in callback and event emitter.
}, function(error, response, metadata) {
  console.log(error, response, metadata);
});

Here's a quick peak at the type of actions your notifications can make:

Notifier

Events

node-notifier is capable of sending click and close events -- handy for triggering specific actions depending on how the user interacts with the notification:

// Open the DWB website!
notifier.on('click', (obj, options) => {
  const spawn = require('child_process').spawn;
  const cmd = spawn('open', ['https://davidwalsh.name']);
});

notifier.on('close', (obj, options) => {});

The sample above allows me to click on the notification to launch my website; one could also use this to trigger other routines on their machine, of course, it simply depends on what the notification is for.

You can get very detailed with your Notification objects and events per platform so be sure to check out the node-notifier API if you really want to dig deep.  Or if you're a sane person, maybe skip out on more notifications in your life!

Recent Features

Incredible Demos

  • By
    Facebook Open Graph META Tags

    It's no secret that Facebook has become a major traffic driver for all types of websites.  Nowadays even large corporations steer consumers toward their Facebook pages instead of the corporate websites directly.  And of course there are Facebook "Like" and "Recommend" widgets on every website.  One...

  • By
    Record Text Selections Using MooTools or jQuery AJAX

    One technique I'm seeing more and more these days (CNNSI.com, for example) is AJAX recording of selected text. It makes sense -- if you detect users selecting the terms over and over again, you can probably assume your visitors are searching that term on Google...

Discussion

  1. Gustavo

    I really liked this package, I’m thinking some scenarios where it can help right now ;). Thanks for the article, David.

  2. Gustavo meyer

    That’s awesome article, David

  3. Ashish Kumar Badtiya

    Looks like the code portion doesn’t get wrapped on mobile devices. So, they got cut

    • Ashish Kumar Badtiya

      Wait, loading issues
      Now it works fine

  4. Awesome post! I just used OS notifications in a JAVA project, but I only got them to work on Mac and not Windows. Can’t wait to try this!

  5. I have implemented same but Mac Osx restrict characters in notification.

    https://stackoverflow.com/a/16248088/1398979

    Any workaround for this?

  6. I love the node-notifier module as well as the CLI.

    Created a little tool which shows a notification if a command exits with an exit code other than 0:
    https://github.com/micromata/cli-error-notifier

    Created some useful aliases with the CLI in my ~/.zshrc

    alias npm-reset="rm -rf node_modules && npm install && npx node-notifier-cli -t 'Done' -m 'npm modules reinstalled' -s Glass -i https://cdn.rawgit.com/npm/logos/31945b5c/npm%20square/n-64.png"
    alias npm-reset-hard="rm -rf node_modules && rm -f package-lock.json && npm install && npx node-notifier-cli -t 'Done' -m 'npm modules reinstalled' -s Glass -i https://cdn.rawgit.com/npm/logos/31945b5c/npm%20square/n-64.png"
    alias yarn-reset="rm -rf node_modules && yarn && npx node-notifier-cli -t 'Done' -m 'npm modules reinstalled' -s Glass -i https://cdn.rawgit.com/yarnpkg/assets/ab1fa0d4/yarn-kitten-circle.png"
    alias yarn-reset-hard="rm -rf node_modules && rm -f yarn.lock && yarn && npx node-notifier-cli -t 'Done' -m 'npm modules reinstalled' -s Glass -i https://cdn.rawgit.com/yarnpkg/assets/ab1fa0d4/yarn-kitten-circle.png"
    
  7. Aatif

    I am using this library on windows, but the problem is that click event is not triggered.

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!