0

I have a file and its structure is like this:

({
    foo: 'bar',
    bar: 'foo'
})

I'm trying to load and read the file in NodeJS so that I can get the object as a variable; what's the best way to do this? Note that I can't change the file's structure.

2 Answers 2

3

You could read the file into a string and eval that string:

var fs = require('fs');
var s = fs.readFileSync('myfile.js', 'utf8');
var x = eval(s);

If necessary, you could modify the string s before calling eval.

I have to agree with mtsr that a solution using JSON.parse is better (both in terms of security and probably performance as well). However, the current data file does not represent a JSON structure due to the extra parenthesis surrounding the object literal.

if you are certain that the object literal {..} is always surrounded by a (..) pair, you can remove them and then attempt to parse the string:

m = s.match(/\(([\s\S]+)\)/);
x = JSON.parse(m[1]);

The [\s\S]+ part of the regexp, matches anything including newline characters. The \( and \) part matches the surrounding parenthesis.

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

3 Comments

Ah eval, I was hoping to avoid this since my coworkers would probably laugh, taunt and generally make jokes about me for the rest of the project!
Using eval is bad advice. Use JSON.parse() instead.
JSON.parse() cannot handle the extra parenthesis. Of course, if this is the problem, one could manually strip them from the string and then process the result through JSON.parse().
1

I would avoid eval. Try

JSON.parse()

instead.

2 Comments

Hmm this doesn't seem to work as when I do: JSON.parse(({ foo: 'bar', bar: 'foo' })), it reports an error :(
+1 for JSON.parse. Edited my answer to include that alternative along with the required removal of the extra parens.

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.