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);
}
});
}
}
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 .
The Readline module provides a way of reading a datastream, one line at a time.
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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With