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:
{
"ingredients":
[
{"name":"Crab","unit":"Tsp","amount":3},
{"name":"Peas","unit":"Cup","amount":12},
{"name":"Basil","unit":"Tbsp","amount":10},
{"name":"Cumin","unit":"Liter","amount":3},
{"name":"Salt","unit":"Tbsp","amount":1}
],
"name":"Boiled Crab with Peas",
"preptime":"13",
"cooktime":"78",
"description":"A boring recipe using Crab and Peas",
"id":"b0e347d5-9428-48e5-a277-2ec114fc05a0"
}
My code is this: It gives an unexpected JSON position 1
fs.readdirSync("./recipes").forEach(file =>{
//let rec = JSON.parse(file);
console.log(JSON.parse(file))
})
Advertisement
Answer
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}`)
}
console.log(JSON.parse(data))
})