2016-07-29 82 views
2

当计算机(运行node.js的计算机)进入睡眠状态时,是否可以让OS X通知我的node.js应用程序?关闭?似乎应该是,但我一直无法找到任何与node.js相关的东西。我确实发现this,但它是在谈论可可应用程序。也许我可以有其他的应用程序(如Cocoa)接收睡眠通知并将其传递给node.js?Node.js/OS X:计算机进入睡眠状态时如何通知node.js应用程序

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

+0

我不确定这是应该在堆栈溢出还是要求不同。但我认为这是一个编程问题,而不是OS X的特定问题。对不起,如果我在错误的地方。 –

+1

我没有在['OS'](https://nodejs.org/api/os.html)模块中看到任何我期望的内容。我的猜测是你可以使用节点的['Child Process'](https://nodejs.org/api/child_process.html)产生一个监听它的shell(或其他语言)脚本,然后通知父节点进程。 –

+1

这可能有助于http://apple.stackexchange.com/questions/27036/possible-to-run-scripts-on-sleep-and-wake –

回答

3

使用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:', '[email protected]:@', 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(); 

其他类型的通知,你可以观察,可以发现here

+0

为了记录,该脚本将阻止我的node.js应用程序的其余部分运行。但是我能够创建一个像@Matthew Herbst所建议的那样运行此脚本并在睡眠即将到来时通知我的主应用程序的子进程。这工作完美。谢谢! –

+0

@tylermackenzie是的,'runLoop()'应该正确地“异步”,以使其与其他代码运行更好地工作,没有想到这一点。 – robertklep

+1

是轻松完成的吗?此外,我能够通过多次调用'Delegate.addMethod'和'nc()'并且替换'NSWorkspaceWillSleepNotification'并创建一个新的“选择器”和回调函数来使它看到多种类型的通知,这似乎工作,被认为是一个好方法? –

相关问题