8

node.jsを使用して大きな(2MB以上)テキストファイルの行を上書きする最良の方法は何ですか?

私の現在の方法は

  • ファイル全体をバッファにコピーします。
  • 改行文字(\n)によってバッファを配列に分割します。
  • バッファインデックスを使用して行を上書きします。
  • 次に、と結合した後、ファイルをバッファで上書きします\n
4

2 に答える 2

4

まず、行の開始位置と終了位置を検索する必要があります。次に、行を置き換える関数を使用する必要があります。ライブラリの1つであるNode-BufferedReaderを使用して、最初の部分のソリューションがあります。

var lineToReplace = "your_line_to_replace";
var startLineOffset = 0;
var endLineOffset = 0;

new BufferedReader ("your_file", { encoding: "utf8" })
    .on ("error", function (error){
        console.log (error);
    })
    .on ("line", function (line, byteOffset){
        startLineOffset = endLineOffset;
        endLineOffset = byteOffset - 1; //byteOffset is the offset of the NEXT byte. -1 if it's the end of the file, if that's the case, endLineOffset = <the file size>

        if (line === lineToReplace ){
            console.log ("start: " + startLineOffset + ", end: " + endLineOffset +
                    ", length: " + (endLineOffset - startLineOffset));
            this.interrupt (); //interrupts the reading and finishes
        }
    })
    .read ();
于 2012-07-30T16:08:47.803 に答える
1

たぶんあなたはパッケージreplace-in-fileを試すことができます

以下のようなtxtファイルがあり、置き換えたいとします。

line1-> line3

line2-> line4

// file.txt
"line1"
"line2"
"line5"
"line6"
"line1"
"line2"
"line5"
"line6"

次に、次のように実行できます。

const replace = require('replace-in-file');

const options = {
    files: "./file.txt",
    from: [/line1/g, /line2/g],
    to: ["line3", "line4"]
};

replace(options)
.then(result => {
    console.log("Replacement results: ",result);
})
.catch(error => {
    console.log(error);
});

詳細については、そのドキュメントを参照してください:https ://www.npmjs.com/package/replace-in-file

于 2020-02-13T04:11:17.080 に答える