'forEach doesn't work with fs in discord.js

I have a small function here but it doesn't work.

function update_counter() { 
  const channels = fs.readFileSync('./channels.json', {"encoding": "utf-8"}); //doesn't work
    channel_count_template.channel_count = 0
    channels.forEach(channel => {    
        channel_count_template.channel_count += 3000; 
        fs.writeFileSync("channels-count.json", JSON.stringify(channel_count_template, null, 2)); 
    })
}

With require, it works, but I have to update the file every time the function gets executed. For a better explanation here is the channels.json file:

[
  {
    "channel": [
      "438766794747896789"
    ],
    "info": {
      "cooldown": 3000
    }
  },
  {
    "channel": [
      "izulköio"
    ],
    "info": {
      "cooldown": 6000
    }
  }
]

Thanks for helping me ;)



Solution 1:[1]

You forgot to parse the JSON string in the file using JSON.parse:

const json = fs.readFileSync('./channels.json', {"encoding": "utf-8"});
const channels = JSON.parse(json)

Without this, you had a string (not an array) in the variable, and a string doesn't have any forEach method.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1