Giter Site home page Giter Site logo

keypress's Introduction

keypress

Make any Node ReadableStream emit "keypress" events

Previous to Node v0.8.x, there was an undocumented "keypress" event that process.stdin would emit when it was a TTY. Some people discovered this hidden gem, and started using it in their own code.

Now in Node v0.8.x, this "keypress" event does not get emitted by default, but rather only when it is being used in conjunction with the readline (or by extension, the repl) module.

This module is the exact logic from the node v0.8.x releases ripped out into its own module.

Bonus: Now with mouse support!

Installation

Install with npm:

$ npm install keypress

Or add it to the "dependencies" section of your package.json file.

Example

Listening for "keypress" events

var keypress = require('keypress');

// make `process.stdin` begin emitting "keypress" events
keypress(process.stdin);

// listen for the "keypress" event
process.stdin.on('keypress', function (ch, key) {
  console.log('got "keypress"', key);
  if (key && key.ctrl && key.name == 'c') {
    process.stdin.pause();
  }
});

process.stdin.setRawMode(true);
process.stdin.resume();

Listening for "mousepress" events

var keypress = require('keypress');

// make `process.stdin` begin emitting "mousepress" (and "keypress") events
keypress(process.stdin);

// you must enable the mouse events before they will begin firing
keypress.enableMouse(process.stdout);

process.stdin.on('mousepress', function (info) {
  console.log('got "mousepress" event at %d x %d', info.x, info.y);
});

process.on('exit', function () {
  // disable mouse on exit, so that the state
  // is back to normal for the terminal
  keypress.disableMouse(process.stdout);
});

License

(The MIT License)

Copyright (c) 2012 Nathan Rajlich <[email protected]>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

keypress's People

Contributors

dominictarr avatar edwardbetts avatar orthographic-pedant avatar tootallnate avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

keypress's Issues

Waiting for keypress within async loop

For some reason the code below is exponentially applying "orders" instead of one at a time. Any idea why?

async.eachSeries(orders, function(order, callback){
    console.log("Fulfill order "+order.id+"?");
    process.stdin.on('keypress', function (ch, key) {
        if (key && key.name == 'enter') {
            return callback(null);
        }
        if(key && key.ctrl && key.name == 'c') {
            process.stdin.pause();
            return callback(null);
        }
    });
}, function(err, results){
    if(err) return callback(err);
    return callback(null, results);
});

Issue when process sent to background

When you start a process and send it to the background, using node foo.js &, the terminal does something with the stdin that causes issues when using keypress.

It appears to freeze the whole node process (such that any ports you are listening on remain unavailable to the system but don't respond). The process itself doesn't respond to any signals except SIGKILL.

This is only the case when we've called process.stdin.setRawMode(true)

The system sends a SIGTTOU at some point after launching, but before becoming unresponsive. I'm wondering if I could listen for that signal and call keypress.disable(process.stdin) or something similar.

I'm using OS X 10.10.1 and this problem reproduces in node v0.10.x.

How to use this library together with prompt?

I want to catch all key presses, but also, use prompt library.

var Prompt = require("prompt")
  , Keypress = require("keypress")
  ;

Prompt.start();
var schema = {
    properties: {
        name: {
            required: true
          , description: "What's your name?"
        }
    }
};

Prompt.get(schema, function (err, result) {
    console.log(err || result);
});

process.stdin.on("keypress", function (ch, key) {
    console.log(key);
    if (key && key.name === "c" && key.ctrl) {
        process.exit();
    }
});

The issue is that after prompt callback is called, keypress events are not triggered anymore.

Is there a solution/work around for this?


http://stackoverflow.com/q/25268882/1420197

Example code doesn't work

process.stdin.setRawMode(true);
^
TypeError: Object # has no method 'setRawMode'

What am I doing wrong?

How can I stop keypress emit when I use readline?

Hey, I use keypress to detect user's key stroke to control my app,
but in some part of my application, I need user input some words using readline,
the stdin have been weird,
Every keypress characters are repeated twice,

So, How to close keypress emit when I use readline?

Is there any event for "Keyrelease" or "key up"?

I am working on JS robotics(with Arduino Uno board) and has created a simplebot.
when i press "up" key car moves forward but when i release the "up" key, car does not stop.
So is there any event like "keyrelease" so that when i release the key, car can stop ?

Implement me. Unknown stdin file type

I have a problem with the example for instance the keyboard event, my application say 'Implement me. Unknown stdin file type' and break my electron application.

How I can solve this? Is a issue?

Thanks, guys, this is my code.

var keypress = require('keypress');

keypress(process.stdin);

process.stdin.on('keypress', function(ch, key) {
    console.log('got "Keypress', key);
});
process.stdin.setRawMode(true);
process.stdin.resume();

piped streams are truncated when keypress is loaded

Over at request/request I documented an issue that is looking increasingly like a problem in keypress rather than the request module.

In a nutshell:

Given this program:

require("keypress")(process.stdin);
var request = require('request');
request.get("https://github.com/request/request/issues/511").pipe(process.stdout);

The command:

node foo.js

prints the entire document, but the command

node foo.js | cat

is truncated after 1024 characters with this error:

stream.js:94
      throw er; // Unhandled stream error in pipe.
            ^
Error: write EPIPE
    at errnoException (net.js:904:11)
    at Object.afterWrite (net.js:720:19)

Taking out the first line (the call to keypress) makes the issue go away.

I assume that this is probably true for most streams - the use of request here is probably not required to recreate the issue.

Can't detect ⌘ key?

Hi everybody!

Is it possible to detect the ⌘ key in any way?
(Another question: Is it possible to detect keystrokes, if the terminal isn't front? E.g. I want to call a node script with a global shortcut from anywhere in my system. Like the Alfred App which is opened via ⌥Space from anywhere.)

Thank you,
Pipo

Project seems abandoned; use this simple workaround instead

I stumbled upon this project while trying to build a custom Node REPL. At first, it looked promising, but, as has been pointed out in other issues, it seems to have been abandoned.

Luckily, it looks as though there is a simple workaround that should get you going without this dependency. I've put the following together with some examples from Node's readline module.

let readline = require('readline');

readline.emitKeypressEvents(process.stdin);

process.stdin.on('keypress', (ch, key) => {
  console.log('got "keypress"', ch, key);
  if (key && key.ctrl && key.name == 'c') {
    process.stdin.pause();
  }
});

process.stdin.setRawMode(true);

keypress doesn't recognize undefined

there are mycodes

var readline = require('readline')
var rl = readline.createInterface(process.stdin, process.stdout)

process.stdin.on('keypress', (c, k) => {
  console.log(c,k);
});


and

const keypress = require('keypress');
keypress(process.stdin);
process.stdin.on('keypress', function (ch, key) {
    console.log('got "keypress"', key);
  if (key && key.ctrl && key.name == 'c') {
    console.log('got "keypress"', key);
    process.stdin.pause();
    process.stdout.write('Connection closed.')
  }
});


I expected these codes work similar, but return different values.
for example, input:1qaz2wsx↵

11 { sequence: '1', name: '1', ctrl: false, meta: false, shift: false }
qq { sequence: 'q', name: 'q', ctrl: false, meta: false, shift: false }
aa { sequence: 'a', name: 'a', ctrl: false, meta: false, shift: false }
zz { sequence: 'z', name: 'z', ctrl: false, meta: false, shift: false }
22 { sequence: '2', name: '2', ctrl: false, meta: false, shift: false }
ww { sequence: 'w', name: 'w', ctrl: false, meta: false, shift: false }
ss { sequence: 's', name: 's', ctrl: false, meta: false, shift: false }
xx { sequence: 'x', name: 'x', ctrl: false, meta: false, shift: false }
{
sequence: '\r',
name: 'return',
ctrl: false,
meta: false,
shift: false
}

and

1qaz2wsx
got "keypress" undefined
got "keypress" { name: 'q', ctrl: false, meta: false, shift: false, sequence: 'q' }
got "keypress" { name: 'a', ctrl: false, meta: false, shift: false, sequence: 'a' }
got "keypress" { name: 'z', ctrl: false, meta: false, shift: false, sequence: 'z' }
got "keypress" undefined
got "keypress" { name: 'w', ctrl: false, meta: false, shift: false, sequence: 'w' }
got "keypress" { name: 's', ctrl: false, meta: false, shift: false, sequence: 's' }
got "keypress" { name: 'x', ctrl: false, meta: false, shift: false, sequence: 'x' }
got "keypress" {
name: 'return',
ctrl: false,
meta: false,
shift: false,
sequence: '\r'
}
got "keypress" {
name: 'enter',
ctrl: false,
meta: false,
shift: false,
sequence: '\n'
}

lower one didn't recognize number key.

keypress blocking event-loop (node v0.12.0)

On node v0.12.0 the event-loop seems to get blocked after hitting a key a few times.

See this simple code:

var keypress = require('keypress');
var c = 0;

setInterval(function() {
  console.log('tick', c++);
}, 1000);

keypress(process.stdin);

process.stdin.on('keypress', function (ch, key) {
  console.log('key pressed');
  if (key && key.ctrl && key.name == 'c') {
    process.exit();
  }
});

process.stdin.setRawMode(true);
process.stdin.resume();

There is a ticker supposed to output tick <counter> every second. On node v0.10.x the ticker outputs its message in the expected interval, no matter how often you press a key.
On node v0.12.0 something blocks the ticker from outputting after hitting, for example, the space-key a few times. The Number of keypresses which are required to make start it block seems to be random. Sometimes it blocks after the first keypress, some other times it takes up to 5 keypresses.

I'm running node on OSX Yosmite.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.