Node.js/OS X:如何在计算机进入睡眠状态时通知Node.js应用程序

Node.js / OS X: How to notify node.js app when computer enters sleep

本文关键字:Node js 应用程序 通知 状态 OS 计算机      更新时间:2023-09-26

当计算机(运行node.js的计算机)进入睡眠或关闭时,是否可以让OS X通知我的node.js应用程序?看起来应该是这样,但我一直找不到任何与node.js相关的东西。我确实发现了这个,但它说的是Cocoa应用程序。也许我可以让其他应用程序(比如Cocoa)接收睡眠通知并将其传递给node.js?

我很乐意听到任何可能为我指明正确方向的建议。

使用nodobjc(它似乎有效,但我还没有很好地测试它):

'use strict';
const $ = require('nodobjc');
// Load the AppKit framework.
$.framework('AppKit');
// Create delegate that gets notified
let Delegate = $.NSObject.extend('Delegate');
// The function that gets called when OS X is going to sleep.
function receiveSleepNote(self, cmd, notif) {
  console.log('going to sleep');
}
Delegate.addMethod('receiveSleepNote:', 'v@:@', receiveSleepNote);
Delegate.register();
// Instantiate the delegate and set it as observer.
let delegate = Delegate('alloc')('init');
let nc       = $.NSWorkspace('sharedWorkspace')('notificationCenter');
nc(
  'addObserver', delegate,
  'selector'   , 'receiveSleepNote:',
  'name'       , $.NSWorkspaceWillSleepNotification,
  'object'     , null
)
// Set up the runloop.
let app = $.NSApplication('sharedApplication');
function runLoop() {
  let pool = $.NSAutoreleasePool('alloc')('init');
  try {
    app('nextEventMatchingMask', $.NSAnyEventMask.toString(),
        'untilDate',             $.NSDate('distantFuture'),
        'inMode',                $.NSDefaultRunLoopMode,
        'dequeue',               1);
  } catch(e) {
    console.error('run loop error', e.message);
  };
  pool('drain');
  process.nextTick(runLoop);
}
runLoop();

您可以在此处找到其他类型的通知。