TypeScript readline.createInterface抛出异常

时间:2017-06-20 15:27:06

标签: node.js typescript

我正在尝试创建一个电子应用。在main.ts中,我构建了我认为是一个相当简单的类(下面),但构造函数不会运行。对readline.createInterface(inputStream)的调用失败。似乎运行时不认为调用fs.createReadStream返回的变量有一个名为' on'的函数。在它上面。

例外是

Uncaught Exception:
TypeError: Cannot read property 'on' of undefined
    at new Interface (readline.js:142:10)
    at Object.exports.createInterface (readline.js:28:10)
    at new FileMonitor (/Users/mikedice/code/electron-rm/app/FileMonitor.js:13:38)
    at App.Main.onReady (/Users/mikedice/code/electron-rm/app/Main.js:27:23)
    at emitTwo (events.js:111:20)
    at App.emit (events.js:191:7)

这是生成它的代码块。

import readline = require("readline");
import fs = require("fs");

export class FileMonitor
{
    constructor(public filePath:string){
        if (!fs.existsSync(filePath)){
            console.log(`file does not exist at path ${filePath}`);
            return;
        }

        var inputStream = fs.createReadStream(filePath);
        var readInterface = readline.createInterface(inputStream);

        readInterface.on('line', (val)=>{
            // when new lines arrive we can publish an event to listeners
            console.log(val);
        });
    }
}

我认为,问题是在文件/Users/mikedice/code/electron-rm/node_modules/@types/node/index.d.ts中fs.createReadStream返回一个ReadStream对象并在同一个文件中读取.createInterface期望NodeJS.ReadableStream和TypeScript将这两种类型视为不同,即使运行时期望它们是相同的。我不确定这个特定问题的解决办法是什么,一般来说,这类问题。看起来该语言的类型系统与运行时不一致,但不确定为什么运行时代码执行时运行时无法解决问题。有什么建议吗?

export function createReadStream(path: string | Buffer, options?: {
    flags?: string;
    encoding?: string;
    fd?: number;
    mode?: number;
    autoClose?: boolean;
    start?: number;
    end?: number;
}): ReadStream;

export function createInterface(input: NodeJS.ReadableStream,
output?: NodeJS.WritableStream, 
completer?: Completer | AsyncCompleter, 
terminal?: boolean): ReadLine;

1 个答案:

答案 0 :(得分:1)

您需要修改readline.createInterface()选项调用以传递属性为input.readline的对象。 createInterface()期望分配输入和/或输出流的对象。

readline.createInterface({input: inputStream});