Skip to content

Instantly share code, notes, and snippets.

@kirbee
Last active January 16, 2023 16:21
Show Gist options
  • Save kirbee/17527231ab621a30e3c8b78fe7638e33 to your computer and use it in GitHub Desktop.
Save kirbee/17527231ab621a30e3c8b78fe7638e33 to your computer and use it in GitHub Desktop.
Small node program reading each keystroke from the command line
const readline = require('readline');
const stdin = process.stdin;
readline.emitKeypressEvents(stdin);
stdin.setRawMode(true);
class Coordinates {
constructor(x = 0, y = 0) {
this.x = x;
this.y = y;
}
incrementY() {this.y += 1}
decrementY() {this.y -= 1}
incrementX() {this.x += 1}
decrementX() {this.x -= 1}
toString() {return `[${this.x}, ${this.y}]`}
}
const coordinates = new Coordinates();
stdin.on('keypress', function (_, key) {
handleKey(key, process);
});
const handleKey = (key, process) => {
if (key) {
switch (key.name) {
case 'up':
coordinates.incrementY();
break;
case 'down':
coordinates.decrementY();
break;
case 'left':
coordinates.decrementX();
break;
case 'right':
coordinates.incrementX();
break;
case 'c':
if (key.ctrl) {
process.exit()
}
}
console.log(`New coordinates: ${coordinates.toString()}`)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment