I have a file object.js which contains a javascript object:
{
key: value,
anotherKey: { a: b }
}
Inside another file, say reader.js, I would like to read from object.js and put that javascript object into a variable which would act as a normal js object
const fs = require("fs");
let content = fs.readFileSync("object.js");
console.log(content); // looks good
let object = { ...content };
console.log(object); // bad and wrong...
// expected: { key: value, anotherKey: { a: b } }
Any ideas how to parse the js object from object.js and put it into a valid object variable?
JSON.parse(JSON.stringify(content)) didn't help.
JSON.stringify()first?contentis just a string at this point, so all you need is to callJSON.parse().object.jsfile is NOT valid JSON and it shouldn't be - it's a JavaScript object, hence it's not parsable withJSON.parseorJSON.stringifyor a combination of both. I just tried to provide more information about what I tried to help others help me faster:)