读取和写入巨大的 json 文件

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

我正在 Mongo ChangeStreams 上工作,并将我的数据库更改(之前和之后)数据包存储在本地系统中,然后另一个脚本读取这些文件并将其上传到 s3。

我的文件夹结构: Parent_Folder -> 帐户 -> 2024-05-23.json

现在,其中一些 json 文件的大小达到了 500Mb,这使得读写非常困难,因为它将文件加载到内存中。另外,JSON 有时会给出

Error: Too long to parse

我当前使用的代码:

async function exportToLocalFile(data, collectionName) { // THIS FUNCTION IS BEING CALLED FOR EVERY CHANGE DETECTED IN DB (frequency is VERY high)
  const currentDate = new Date()
  const year = currentDate.getFullYear()
  const month = (currentDate.getMonth() + 1).toString().padStart(2, '0')
  const day = currentDate.getDate().toString().padStart(2, '0')
  const filePath = `${LOCAL_AUDIT_LOGS_STORAGE_FOLDER}/${collectionName}/${year}-${month}-${day}.json`

  checkAndDeleteDayOlderFiles(collectionName)

  // READING DATA HERE:: Append data if file exists already
  const existingData = readJSONFile(filePath) || []
  console.log({ existingData })

  let finalObject = [data, ...existingData]

  console.log({ finalObject })

  // Write updated JSON back to file
  fs.writeFileSync(filePath, JSON.stringify(finalObject, null, 2), 'utf-8')

  console.log('Data written to file successfully. ' + filePath)
}

function readJSONFile(filePath) {
  try {
    const fileExists = fs.existsSync(filePath)
    if (fileExists) {
      const data = fs.readFileSync(filePath, 'utf8')
      return JSON.parse(data)
    } else {
      return null
    }
  } catch (error) {
    console.error('Error reading file:', error)
    return null
  }
}


/// UPLOADING on s3 :::

async function readAndExportToS3(directory) {
  let files = fs.readdirSync(directory)

  for (let file of files) {
   
    const filePath = path.join(directory, file)
    console.log({ filePath })

    // Check if the file is a directory
    if (fs.statSync(filePath).isDirectory()) {
      console.log('Its a directory!')
      await readAndExportToS3(path.join(directory, file))
    } else {
      console.log("Its a file, let's upload!")
      const key = path.join(directory, file).replace(/\\/g, '/')
      const finalKey = key.split('db_audit_logs/')[1]
      let fileContent = fs.readFileSync(filePath).toString()

      // Upload the file to S3
      const uploadParams = {
        Bucket,
        Key: finalKey,
        Body: fileContent,
        ContentType: 'application/json',
      }

      try {
        let data = await s3.upload(uploadParams).promise()
        console.log('Uploaded sucessfully :: ', data.Location)
      } catch (err) {
        console.log('Error uploading ', file, { err })
      }


    }
  }
}

只是想知道是否有更好、更快、更有效的方式来读取/写入/解析此类 JSON 文件。任何朝着正确方向的推动肯定会有所帮助。欢迎任何建议。

node.js json
1个回答
0
投票

正如很多人所说,json 非常消耗内存,因为它要求您在使用它之前将整个数据加载到内存中,并且应该仅用于数据传输,而不是存储。

我最好的选择是使用一个简单的阅读器,它可以逐行读取文件,并且根据第一个字符或单词,它可以返回整行。

或者,动态处理大数据的最简单方法就是使用任何类型的数据库,但最简单的是sqlite3,因为它允许您使用单个文件作为数据库,并且它当然不会加载内存中的全部数据。

© www.soinside.com 2019 - 2024. All rights reserved.