gpt4 book ai didi

javascript - 计算机进入休眠状态时 Node.js/OS X : How to notify node. js 应用程序

转载 作者:搜寻专家 更新时间:2023-11-01 00:39:48 25 4
gpt4 key购买 nike

当计算机(运行 node.js 的计算机)进入休眠或关闭时,是否可以让 OS X 通知我的 node.js 应用程序?似乎应该如此,但我找不到任何与 node.js 相关的内容。我确实找到了 this但它谈论的是 Cocoa 应用程序。也许我可以让其他应用程序(如 Cocoa)接收 sleep 通知并将其传递给 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();

可以找到您可以观察到的其他类型的通知 here .

关于javascript - 计算机进入休眠状态时 Node.js/OS X : How to notify node. js 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38668938/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com