Skip to content

JSON data not working using fs in javascript

I am trying to parse a json file and get some errors. It is in a directory under my js file with the fs in a folder called “recipes” with 3 json files all representing a seperate object. Here’s the json of all 3 that are similar:

    "name":"Boiled Crab with Peas",
    "description":"A boring recipe using Crab and Peas",

My code is this: It gives an unexpected JSON position 1

fs.readdirSync("./recipes").forEach(file =>{
    //let rec = JSON.parse(file);


readdirSync could return name string, binary, or dirent object. Neither is the file contents. The custom readFiles is what you need.

const fs = require('fs')
const path = require('path')
const ROOT_DIR = './contents'
const readFiles = (dir, cb) => {
  try {
    fs.readdirSync(dir).forEach(file =>{
      fs.readFile(path.join(dir, file), 'utf-8', cb)
  } catch (e) {
    console.log(`Failed to open the directory ${e.path} `)
readFiles(ROOT_DIR, (err, data) => {
  if (err) {
    console.log(`Failed to read file: ${err.path}`)