【问题标题】:Angular - Efficient way to parse 10000 rows of csv/tsv fileAngular - 解析 10000 行 csv/tsv 文件的有效方法
【发布时间】:2021-12-29 06:13:00
【问题描述】:

我正在寻找一种更充分的方法(或 lib)来解析包含大约 5000 ~ 10000 行的 csv/tsv(使用它来呈现带有 cdk 虚拟滚动的表格以预览文件)。对于这么多的行,我目前的实现是相当香蕉。

this.httpClient.get(this.dataSrc, {
  headers: {
    Accept: 'text/plain'
  },
  responseType: 'text'
}).subscribe(res => {
  // handles tsv or csv content
  const lines = res.split(/\r|\n/);
  const separator = lines[0].indexOf('\t') !== -1 ? '\t' : ',';
  this.parsedCSV = lines.map(l => l.split(separator));
});

【问题讨论】:

  • fast-csv 是一个非常轻量级的包。

标签: javascript angular csv csv-parser


【解决方案1】:

看起来不错,但是解析大量数据会冻结线程。您应该休眠并等待线程,这样解析器就不会冻结。

这是我的做法,看看吧。

const sleep = (msTime) => {
 return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve();
    }, msTime);
  });
}

const parse(csv, onProgress) => {
  const lineSplitter = RegExp('\r|\n', 'g');
  const result = []
  var index =0;
  let match;
  // split one each time, so the thread won't freeze
  while ((match = lineSplitter.exec(csv)) !== null) {
    const line = match[0];
    const separator = line.indexOf('\t') !== -1 ? '\t' : ',';
    result.push(line.split(separator))
    if (index % 30 === 0)
       await sleep(10); // This will make sure the thread won't freeze
    if (onProgress)
       await onProgress((index / lines.length) * 100);
    index++;
  }
 return result;
}

【讨论】:

  • 你好,艾伦。我想知道,你能在你的工作中使用英文拼写检查器吗?这将极大地帮助志愿编辑。
猜你喜欢
  • 1970-01-01
  • 2018-12-31
  • 2012-07-04
  • 2019-03-11
  • 2017-03-06
  • 1970-01-01
  • 2012-12-09
  • 2019-10-20
  • 2012-05-28
相关资源
最近更新 更多