nodejs keydown/keyup events

后端 未结 4 1026
忘了有多久
忘了有多久 2021-01-13 03:58

I\'m interested in seeing if it\'s possible to bind functions to a user pressing/releasing a key on the keyboard.

So far, I\'ve been able to get key press events wit

4条回答
  •  梦毁少年i
    2021-01-13 04:49

    So I figured a workaround the limitations of stdin to get this to work.

    Basically I use the SDL library (along with its node bindings) to run a program in the background that listens on the keyboard for input.

    To do this:

    • Ensure you are running Node version ~0.10. (Apparently the way C bindings on node work a little differently in 0.11?)
    • Install sdl, sdl_ttf, and sdl_image through homebrew (on a mac)
    • npm install --save https://github.com/creationix/node-sdl/tarball/master

    And then something along the lines of:

    var sdl = require('sdl');
    
    sdl.init(sdl.INIT.VIDEO);
    
    while (true) {
        var e;
        while (e = sdl.pollEvent()) {
            console.log(e);
        }
    }
    

    SDL_PollEvent requires SDL be initialized with SDL_INIT_VIDEO, which in the script above (on a mac) starts a separate application in the dock that draws nothing, but needs to be focused to accept input.

    While it's technically true that ANSI terminals simply do not support keyup events, this workaround totally lets one grab keyup events in Node (albeit requiring some GUI-based system to function, i.e. most likely will not work over ssh).

提交回复
热议问题