Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript + NodeJS readline property missing

I'm working on a small project in TypeScript with tsc -v 2.4.2 and Node v6.10.3.

I would like to capture keypresses in the CLI, so I tried to import * as readline from 'readline' and then later use readline.emitKeyPressEvents(process.stdin), but it complains that the property emitKeyPressEvents is not found on typeof readline.

I have also done npm install --save @types/node.

Here's a M(N)WE:

import * as readline from "readline";
import {SIGINT} from "constants";

export class InputManager
{
    private _currentStates: Array<IKeyEntity>;
    private _oldStates: Array<IKeyEntity>;

    public constructor()
    {
        // Throws error, won't compile
        readline.emitKeyPressEvents(process.stdin);
    }

    public handleInput()
    {
        if (process.stdin.isTTY)
            process.stdin.setRawMode(true);

        process.stdin.on('keypress', (str: string, key: any) => {
            process.stdout.write('Handling keypress ['+str+']');

            if (key && key.ctrl && (key.name == 'c' || key.name == 'l'))
            {
                process.kill(process.pid, SIGINT);
            }
        });
    }
}
like image 804
Mori no Ando Avatar asked Sep 13 '17 21:09

Mori no Ando


People also ask

What is createInterface in node JS?

The method createInterface() takes two parameters – the input stream and output stream – to create a readline interface. The third parameter is used for autocompletion and is mostly initialized as NULL .

What is readline () in Javascript?

The Readline module provides a way of reading a datastream, one line at a time.

What is readline module in node JS?

Readline Module in Node.js allows the reading of input stream line by line. This module wraps up the process standard output and process standard input objects. Readline module makes it easier for input and reading the output given by the user.

How do I read a file line by line in node?

const readline = require('readline'); Since readline module works only with Readable streams, so we need to first create a readable stream using the fs module. // but from a readable stream only. The line-reader module provides eachLine() method which reads the file line by line.


1 Answers

The method is indeed missing from the node typings. Its correct name is actually emitKeypressEvents (with a lower-case p), but that one is also missing. I assume this is a simple oversight, so I've submitted a PR with the addition to DefinitelyTyped. This might take a while to process (around a week, if all goes well), but in the mean time you can type check your code by adding a local declaration to the file containing InputManager:

declare module 'readline' {
  export function emitKeypressEvents(stream: NodeJS.ReadableStream, interface?: ReadLine): void;
}
like image 188
Oblosys Avatar answered Oct 30 '22 07:10

Oblosys