Nodejs如何优化编写非常大的xml文件



我有一个巨大的CSV(1.5GB(,我需要逐行处理它并构建2个xml文件。当我单独运行处理时,我的程序大约需要4分钟才能执行,如果我也生成xml文件,那么生成两个9GB的xml文件需要2.5个多小时。

我编写xml文件的代码非常简单,我使用fs.appendFileSync来编写打开/关闭xml标记及其内部的文本。为了清理数据,我对xml标记中的文本运行了这个函数。

  function() {
    return this.replace(/&/g, "&")
      .replace(/</g, "&lt;")
      .replace(/>/g, "&gt;")
      .replace(/"/g, "&quot;")
      .replace(/'/g, "&apos;");
  };

有什么可以优化的东西来减少执行时间吗?

fs.appendFileSync()是一个相对昂贵的操作:它打开文件,附加数据,然后再次关闭。

使用可写流会更快:

const fs = require('node:fs');
// create the stream
const stream = fs.createWriteStream('output.xml');
// then for each chunk of XML
stream.write(yourXML);
// when done, end the stream to close the file
stream.end();

我做了两件事,大大缩短了执行时间(到30分钟(。

  1. 设置ENV变量UV_THREADPOOL_SIZE=64
  2. 缓冲我对xml文件的写入(在20000个关闭标记后,我将缓冲区刷新到文件(