UNPKG

click.js

Version:

Subscribe to system mouse/keyboard events.

73 lines (63 loc) 2.33 kB
/* @package click.js * @author Jochem Stoel (http://jochemstoel.github.io/) */ module.exports = function() { /* Child process writes detected event to stdout as array. */ var child, callbacks; /* This object will contain your callbacks. */ callbacks = { } /* This will spawn the child process. */ this.start = () => { child = require('child_process').spawn(__dirname + '/clik.exe', []) /* Create object using child response and ignore errors. */ function objectify(line) { try { /* Evaluate response to create real array. */ var event = eval(line) /* I don't understand this but otherwise it does not work. */ event = JSON.parse(JSON.stringify(event)) /* The first item in event is the event type, the rest is details */ var type = event[0] event = event.splice(0) /* Return the object. */ return { type: type, event: event } } catch (cum) { /* Better to ignore exceptions. */ } } /* When a line is received from the child process... */ child.stdout.on('data', (line) => { /* Objectify the line. */ line = String(line).trim() var event = objectify(line) /* Try callback function. */ try { callbacks[event.type](event) } catch (cum) { /* The callback does not exist, no reason to handle. */ } /* Try catch all function. */ try { callbacks['*'](event) } catch (cum) { /* The callback does not exist, no reason to handle. */ } }) return this } /* When called, kill the child. */ this.done = () => { child.kill() return this } /* Allow user to define callbacks using common on() method. */ this.on = (type, callback) => { callbacks[type] = callback return this } /* It is always about this and never about that. */ return this }