Reading External JSON file - NodeJs

Viewed 102

I'm trying to read an external JSON file in NodeJS, but its returning undefined at the start of the JSON. I'm using readFileSync since this is a config file, and this process needs to be completed first before moving on.

NOTE: There is NO white space at the top of the external file.

EXTERNAL JSON FILE

{
   email:{
       username: "someUserName",
       password: "somePassword"
   },
   database: {
      username: "databaseUser",
      password:"datbasePassword"
   }
}

NODE JS

"use strict";

const fs = require("fs");
let rawData = fs.readFileSync("/run/secrets/secrets_file.json");
let secrets= JSON.parse(rawData);

console.log("SECRETS: ", secrets);

RETURNS

undefined:1
data = {

SyntaxError: Unexpected token d in JSON at position 0
    at JSON.parse (<anonymous>)

What's happening here?

2 Answers

Your JSON file is not valid JSON. You need to quote the keys.

{
    "email": {
        "username": "someUserName",
        "password": "somePassword"
    },
    "database": {
       "username": "databaseUser",
       "password": "datbasePassword"
    }
}

Have you check And key "d" in json which is not visible in the front of screen. that may written by mistake some where else in the file

Related