使用Node.js的系统通知

发布于:2021-02-18 00:00:19

0

233

0

Nodejs 系统通知 Web

如今,通知可能是上天的恩赐,也可能是我们生存的祸根。你手机上安装的每个应用都想要访问通知,桌面应用也一样,现在我们有了一个Web通知API和一个Web推送API,以防你的生活中没有足够的通知。日历上的约会提醒总是很受欢迎的(否则我就会忘记每一件事),但Wacky Mini Golf真的需要通知我,我已经4天没打了吗?可能不会。

总之,我在考虑通知,以及如何使用它们来记住我需要在今天的特定时间做的事情;例如,提醒自己在不定期的日子去吃午饭、骑自行车或去学校接儿子。作为一个JavaScript迷,我决定使用Node.js来创建Mac通知,我很快找到了答案:node- notification !让我们一起来看看!

创建一个简单的通知

node-notifier 在Mac和Windows PC上均可使用。通知的范围从非常简单到高级,所以让我们首先创建一个非常简单的通知:

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
});

您可以提供notifier 基本的一样title,message和icon,然后再进一步添加内容的图像,声音,甚至控制按钮,显示通知。

进阶通知

您可以使用来创建功能丰富的高级通知node-notifier,包括回复功能,控制通知按钮标签等。以下是更高级的示例:

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);
});

这是您的通知可以执行的操作类型的一个快速高峰:

Notifier

大事记

node-notifier 能够发送 click 和close 事件-根据用户与通知的交互方式方便地触发特定操作:

// 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) => {});

上面的示例使我可以单击通知以启动我的网站;一个人也可以使用它来触发他们机器上的其他例程,当然,这仅取决于通知的目的。

您可以在每个平台上获得有关Notification对象和事件的非常详细的信息,因此,node-notifier 如果您真的想深入了解,请确保签出API。或者,如果您是一个理智的人,也许可以跳过生活中的更多通知!