Error when trying to parse a string into JSON from .json file in node js

var jsonObject = collages;

file.writeFile('collage.json', JSON.stringify(jsonObject), function(err){
    if (err) throw err;
    console.log('Success');
});


var result = '';
result += file.readFile('collage.json', 'utf-8', function(err, data) {
    if(err) throw err;
    console.log(data);
});
JSON.parse(result);

I'm getting an "SyntaxError: Unexpected token u - at Object.parse(native)"

I'm new to JSON and I can't seem to recreate the object that I write out. When I print out result I have the stringified json object, however when I try to parse that string the error is given. The object collages is simply an array of layer objects which hold 6 fields (x value, y value, width...etc). Any help would be much appreciated, I want to read in the JSON object so that I can recreate the collage when it is read in.

file.readFile is an asynchronous action and you are acting like it is synchronous.

readFile is asynchronous, so you just need to rearrange your code a bit:

var result = null;

file.readFile('collage.json', 'utf-8', function(err, data) {
    if(err) throw err;
    result = JSON.parse(data);
});

Remember that with asynchronous functions, you have to execute dependent code in the callback.

You can do this synchronously using readFileSync for example:

var result = file.readFileSync('collage.json').toString();

In the case of a json file, Node.js provides an even simpler way to accomplish this:

var result = require('./callage.json');

require will notice the .json extension and parse the file as json for you.

http://nodejs.org/api/fs.html#fs_fs_readfilesync_filename_options http://nodejs.org/api/modules.html#modules_file_modules