1

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.

2
  • 1
    Why would you call JSON.stringify() first? content is just a string at this point, so all you need is to call JSON.parse(). Commented Feb 13, 2019 at 17:50
  • @MTCoster, the point was that the object.js file is NOT valid JSON and it shouldn't be - it's a JavaScript object, hence it's not parsable with JSON.parse or JSON.stringify or a combination of both. I just tried to provide more information about what I tried to help others help me faster:) Commented Feb 13, 2019 at 19:23

2 Answers 2

4

If the file is a JS file, you could consider them as a module and export them

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I solved it by adding module.exports = { ... } at the beginning of the object.js file and then using let object = eval(content) in reader.js, which works perfectly (eval is safe in my case since it's a startup script)!
0

fs.readFileSync will return the content of the file as a string. You should parse that string into a JavaScript object using JSON.parse(content). However, your file doesn't seem to be valid JSON - you must wrap your keys with " and any string values with " as well.

1 Comment

Thanks, the point was that the object.js file is not JSON, but a JavaScript object:)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.