gpt4 book ai didi

node.js - TypeScript readline.createInterface 抛出异常

转载 作者:太空宇宙 更新时间:2023-11-04 00:20:40 26 4
gpt4 key购买 nike

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

异常(exception)是

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;

最佳答案

您需要修改您的readline.createInterface() options 调用以传递具有 input.readline 属性的对象。 createInterface() 需要一个分配了输入和/或输出流的对象。

readline.createInterface({input: inputStream});

关于node.js - TypeScript readline.createInterface 抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44657189/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com