Search code examples
javascriptjsonnode.jswritefile

Empty JSON with Nodejs writeFile


I am trying to write to a JSON file with NodeJS. After writing I have an empty JSON file when using node's writeFile function. When I console.log all the data is correct in my terminal.

const fs = require('fs')
const path = require('path')

fs.readFile('items.csv', 'utf-8', (err,data) => {

  let lines = data.split('\n')

  let result = []

  let headers = lines[0].split(',')

  const noClass = 'NoClass'
  result[noClass] = 0

  for(var i = 1; i < lines.length; i++) {

    let currentLine = lines[i].split(',')

    if(currentLine[2] === '' || currentLine[2] === undefined) {
      result[noClass]++
    } else {
      let merchandiseHierarchy = currentLine[2].split(' : ')

      let subClass = merchandiseHierarchy[2]

      if(!result[subClass]) {
        result[subClass] = 0
      }
      result[subClass]++
    }

  }

  console.log(result)
  fs.writeFile('items.json', result)

})

Solution

  • Your problem is the combination of:

    let result = []
    

    and

    const noClass = 'NoClass'
    result[noClass] = 0
    

    An array [] does not have properties that will be serialized when saved as JSON. If you want to use an object with properties, then it has to be:

    let result = {}
    

    Beside that you need to write:

    fs.writeFile('items.json', JSON.stringify(result))