0

Below is the way I usually use to safely parse local JSON data in Node environment, mostly config files and some other relevant data:

const fs = require('fs')

let localDb
let parsedData

try {
    localDb = fs.readFileSync('./file.json', 'utf8')
    parsedData = JSON.parse(localDb)
} catch (err) {
    throw err
}

exports.data = parsedData

In the end, I export the parsed data from the JavaScript file for usage. While this works perfectly fine, I'm curious to know if there are better ways to do the same thing with a functional approach.

cinnaroll45
  • 2,661
  • 7
  • 24
  • 41
  • 1
    From [my understanding of this answer](https://stackoverflow.com/a/7165572/215552), you can include JSON by using `const data = require('./file.json')`... – Heretic Monkey May 31 '17 at 22:05
  • I don't get the catch throw statement, in the end it will break, why catch and then throw it anyhow, is it not easier to just let it crash? Or is this simplified for a MCVE? – Icepickle May 31 '17 at 22:08

1 Answers1

2

Just wrap your code inside a function and export the return of that function:

const fs = require('fs')

function parseDBData(name, coding) {
  let localDb;
  let parsedData;

  try {
      localDb = fs.readFileSync(name, coding);
      parsedData = JSON.parse(localDb);
  } catch (err) {
      throw err;
  }
}

exports.data = parseDBData('./file.json', 'utf8');

p.s. with node you can directly get the JSON files content through require:

exports.data = require('./file.json');
quirimmo
  • 9,800
  • 3
  • 30
  • 45