简体   繁体   中英

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

Is it possible to have OS X notify my node.js app when the computer (that node.js is running on) is entering sleep or shutting down? Seems like it should be, but I haven't been able to find anything node.js related. I did find this but it's talking about Cocoa apps. Maybe I could have some other app (like Cocoa) receive the sleep notification and pass that to node.js?

I'd love to hear any suggestions that might point me in the right direction.

Using nodobjc (it seems to work, but I haven't tested this very well):

'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();

Other types of notifications that you can observe can be found here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM