在 NodeJS 中编辑大型(1.5gb)文本文件的最后部分

问题描述 投票:0回答:1

我的工具将末尾带有逗号的小 json 块附加到一个 txt 文件中,该文件最初以

[
作为第一个字符,以便创建一个完整的 JSON 格式文本文件,如下所示,

{data: text1},

txt 文件看起来像是在一天结束时,

[{data: text1},{data: text2},{data: text3},

所以我必须删除文本末尾的最后一个逗号并添加一个

]
使其成为有效的 JSON,但是这个文件大小约为 1.5GB,所以我不知道如何在 NodeJS 中编辑它以便使其有效的 JSON 文件。

javascript node.js stream readline large-files
1个回答
0
投票
const fs = require('fs');

// Input and output file paths
const inputFile = 'input.json';

// Open the file for reading and writing
fs.open(inputFile, 'r+', (err, fd) => {
  if (err) {
    console.error('Error opening the input file:', err);
    return;
  }

  // Move to the end of the file
  fs.fstat(fd, (err, stats) => {
    if (err) {
      console.error('Error reading file information:', err);
      fs.close(fd, () => console.log('Closed the input file due to error.'));
      return;
    }

    const endPosition = stats.size;

    // Create a buffer for reading
    const buffer = Buffer.alloc(1); // Read only one byte (comma)

    // Read the last byte in the file
    fs.read(fd, buffer, 0, buffer.length, endPosition - 1, (err, bytesRead, data) => {
      if (err) {
        console.error('Error reading the last byte:', err);
        fs.close(fd, () => console.log('Closed the input file due to error.'));
        return;
      }

      // Check if the last byte is a comma
      if (data[0] !== 44) { // Unicode code for comma is the same as ASCII
        console.log('The last character is not a comma.');
        fs.close(fd, () => console.log('Closed the input file.'));
        return;
      }

      // If the last byte is a comma, replace it with a closing bracket
      const closingBracket = Buffer.from(']', 'utf8'); // Use UTF-8 encoding
      fs.write(fd, closingBracket, 0, closingBracket.length, endPosition - 1, (err) => {
        if (err) {
          console.error('Error writing to the file:', err);
        } else {
          console.log('Replaced the comma with a closing bracket.');
        }
        // Close the input file
        fs.close(fd, () => console.log('Closed the input file after modification.'));
      });
    });
  });
});
© www.soinside.com 2019 - 2024. All rights reserved.