Read and execute a file as a variable in NodeJS

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.

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

var fs = require('fs');
var s = readFileSync('myfile.js', 'utf8');
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.

I would avoid eval. Try

JSON.parse()

instead.