如何将流转换为打字稿中的变量

How to convert stream into variables in typescript

有一个输入文件(file.in)。

4  
5   
1 2  
2 4  
3 1  
3 4  
4 2  

在打字稿中,逐行读取输入文件。

const graphsMain = () => {

    let lineReader = require('readline').createInterface({
        input: require('fs').createReadStream('file.in')
    });

    lineReader.on('line', function (line) {
        console.log('Line from file:', line);
    });
}

graphsMain();

在 C++ 中,我可以通过编码来做到这一点。

#include <iostream>

using namespace std;

bool A[10][10];

int main() {
  int x, y, nodes, edges;
  cin >> nodes; // Number of nodes
  cin >> edges; // Number of edges
  for (int i = 0; i < edges; ++i) {
    cin >> x >> y;
    A[x][y] = true; 
  }

  return 0;
}

但是,我不知道如何在打字稿中实现。请随时发表评论。

我认为这里的问题是,如果您是从 C++ 进入 Javascript 世界,那么在您编写的代码实际执行方式方面存在很大的概念差异。 C++ 严重依赖同步执行,而 Javascript 世界更关注异步执行。

您尝试解决的具体问题将通过使用您尝试使用的异步节点 APIs 以这种方式实现:

// imports, or require()s as in your code are like conceptually equivalent
// to #include in C++, hence should be at the beginning of the file, not somewhere
// in the middle.
import * as fs from 'fs'
import * as readline from 'readline'

const graphsMain = () => {
    let lineReader = readline.createInterface({
        input: fs.createReadStream('file.in')
    });

    let lineCount = 0;
    let nodes: number | undefined
    let edges: number | undefined
    let buffer: number[][] = []
    lineReader.on('line', function (line) {
        console.log('Line from file:', line);
        if (lineCount == 0) {
          nodes = parseInt(line) 
        } else if (lineCount == 1) {
          edges = parseInt(line)
        } else {
          const coordinates = line.split(' ').map((item) => parseInt(item)) 
          buffer.push(coordinates)
        }
        lineCount++
    });

    lineReader.on('close', function () {
        console.log('end. I got these values:', nodes, edges, buffer)   
    });
}

graphsMain();

也就是说,您可以通过多种不同的方式解决它,包括您可能更熟悉的 fs.readFileSync 之类的同步 API。

虽然我觉得您的 Javascript 旅程才刚刚开始,但我强烈建议您阅读一些关于整个生态系统依赖于异步代码执行的重点。 Mozilla MDN 有一系列很棒的文章解释了这一切。