【问题标题】:NodeJS - fs.createReadStream() - how to cut off chunks at a certain point?NodeJS - fs.createReadStream() - 如何在某个点切断块?
【发布时间】:2020-10-08 19:12:52
【问题描述】:

我有一个大的 XML 文件 (2GB),如果满足某个条件,我需要添加一个新行。示例:

<chickens>
    <chicken>
        <name>sam</name>
        <female>false</female>
    </chicken>
    <chicken>
        <name>julia</name>
        <female>true</female>
    </chicken>
    // many many more chickens
</chickens>

到:

<chickens>
    <chicken>
        <name>sam</name>
        <female>false</female>
    </chicken>
    <chicken>
        <name>julia</name>
        <female>true</female>
        <canLayEggs>true</canLayEggs> // <- Add this line if female is true;
    </chicken>
    // many many more chickens
</chickens>

但是,我面临的问题是,有时块会像 &lt;female&gt;true 一样被切断 然后下一个块以&lt;/female&gt;开始

这是我的代码:

const fs = require("fs");
const input = "input.xml";

const MAX_CHUNK_SIZE = 50 * 1024 * 1024; //50 MB
const buffer = Buffer.alloc(MAX_CHUNK_SIZE);

let readStream = fs.createReadStream(input, "utf8", {
    highWaterMark: MAX_CHUNK_SIZE,
});
let writeStream = fs.createWriteStream("output.xml");

readStream.on("data", (chunk) => {
    let data = chunk;
    if (data.includes("<category>f</category>")) {
        data = data.replace(
            /<female>true<\/female>/g,
            "<female>true</female><canLayEggs>true</canLayEggs>"
        );
    }
    writeStream.write(data, "utf-8");
});

readStream.on("end", () => {
    writeStream.end();
})

我尝试过 Google,但似乎找不到合适的术语,而且那里的许多教程并没有真正涵盖这一点。任何帮助表示赞赏。

【问题讨论】:

    标签: node.js xml fs readfile


    【解决方案1】:

    您正在读取每个块 50MB。所以在on data回调中,你可以调用:

    readStream.destroy();
    

    另外,你不需要初始化 50MB 大小的缓冲区,这里没有使用它,在文本替换之后它可能超过 50MB。

    很好,当 readStream 关​​闭时你关闭 writeStream。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-18
      • 1970-01-01
      • 2020-02-14
      • 2020-03-30
      • 1970-01-01
      相关资源
      最近更新 更多