Aminadav Glickshtein
Aminadav Glickshtein

Reputation: 24600

How to check when the computer is idle in NodeJS?

I want to run a process in the background in NodeJS, that wait until the computer not in use for 10 minutes. I mean the user do not touch the keyboard or the mouse.

In other words: I want to listen to keyboard and mouse events in any window, and notify my app when it is happend.

For this mission, I able to use plain node, or nw.js or electron.

I think that I must to use a C++, native module and DLL's. But I hope there is a better and simple solution.

Do you have?

Upvotes: 6

Views: 5285

Answers (4)

Divek John
Divek John

Reputation: 131

I reached here somehow googling for the same thing in electron and if you too proceed, this is how I figured it out from Electron Power monitor API's

const {powerMonitor} = require('electron'); 
const idle = powerMonitor.getSystemIdleTime() // it returns in seconds when I am writing this
console.log('Current System Idle Time - ', idle); 

Upvotes: 1

bithavoc
bithavoc

Reputation: 1539

You can try https://github.com/bithavoc/node-desktop-idle which works on macOS, Windows, Linux, FreeBSD and OpenBSD. I built it for Electron but it works in Node.js in general.

Upvotes: 2

tmatthews
tmatthews

Reputation: 15

I was able to get the user's idle time on OSX using ioreg from this previous answer.

var child_process = require('child_process');

function idleTime(callback) {
    var command = `ioreg -c IOHIDSystem | awk '/HIDIdleTime/ {print $NF/1000000000; exit}'`;
    child_process.exec(command, function(err, stdout, stderr) {
        return err ? callback(err) : callback(null, stdout.trim());
    });
}

setInterval(function() {
    idleTime(function(err, duration) {
        console.log(`idle for ${Math.round(duration)} seconds`)
    })
}, 1000);

Upvotes: 0

Vadim Macagon
Vadim Macagon

Reputation: 14847

There's a Node module for that: https://github.com/paulcbetts/node-system-idle-time

Upvotes: 1

Related Questions