2017-06-20 174 views
1

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

唯一的例外是

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对象和相同的文件readline.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

您需要修改readline.createInterface()选项调用传递对象与物业input.readlinecreateInterface()需要分配输入和/或输出流的对象。

readline.createInterface({input: inputStream}); 
+0

行了。您的建议工作,也工作: readline.createInterface(inputStream,null,null,null); – MikeDice

+1

@MikeDice如果此答案解决了您的问题,请考虑将其标记为已通过点击绿色复选标记。 – Motti