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

  • By
    I&#8217;m an Impostor

    This is the hardest thing I've ever had to write, much less admit to myself.  I've written resignation letters from jobs I've loved, I've ended relationships, I've failed at a host of tasks, and let myself down in my life.  All of those feelings were very...

  • By
    CSS 3D Folding Animation

    Google Plus provides loads of inspiration for front-end developers, especially when it comes to the CSS and JavaScript wonders they create. Last year I duplicated their incredible PhotoStack effect with both MooTools and pure CSS; this time I'm going to duplicate...

Incredible Demos

  • By
    PHP Woot Checker &#8211; Tech, Wine, and Shirt Woot

    If you haven't heard of Woot.com, you've been living under a rock. For those who have been under the proverbial rock, here's the plot: Every day, Woot sells one product. Once the item is sold out, no more items are available for purchase. You don't know how many...

  • By
    Introducing MooTools ScrollSide

    This post is a proof of concept post -- the functionality is yet to be perfected. Picture this: you've found yourself on a website that uses horizontal scrolling instead of vertical scrolling. It's an artistic site so you accept that the site scrolls left to right.

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?

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