Grzes Slania
Grzes Slania

Reputation: 602

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)

})

Upvotes: 0

Views: 5979

Answers (3)

Ademola Sodiq
Ademola Sodiq

Reputation: 1

This fs.writeFile('items.json', result) will never work. fs.writeFile takes 3 - 4 argument so to say and your result must be turn to a string using JSON.stringify() then pass your result into the bracket

Try

fs.writeFile('items.json', JSON.stringify(result), "utf8", (err) => console.log(err));

That should do it and asychronously

Upvotes: 0

t.niese
t.niese

Reputation: 40882

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))

Upvotes: 3

Yogesh_D
Yogesh_D

Reputation: 18809

You should change the writing to file code to, fs.writeFileSync('items.json',JSON.stringify(result))

This will eliminate the two issues you have:

  1. You need to convert your result object to a string representation. If you want the file to be human readable, I would recommend, JSON.stringify(result, null,2), this will indent the file nicely. Do remember that if the result object is big and the output is again going to be programatically consumed, I would recommend leaving out the indentation as it has a space overhead.

  2. writeFileSync will ensure your program flow doesn't continue till the file write operation is done.

Upvotes: 1

Related Questions