JavaScript Node.js - using JSON objects as variables node in json,node json from file,node json from

As part of a test scenario, I would like to use some large JSON objects. I would like to store these in a separate directory, and then import each object as I need them.

Currently I am using the following method:

var t1 = require('./sample_data/t1.json')

var t2 = require('./sample_data/t2.json')

however am seeing out of date data, im guessing due to require cache.

I have tried exporting each object, however I then get a wrapper object around the JSON I require that breaks my tests

Can anyone advise? Is there a better way to do this?

Regards, Ben.

UPDATE: My issue is that I see cached results as I tweak the stored JSON

Answer:1

I dont know if its a better way but you can also do it using the File System module like this:

fs.readFile('./sample_data/t1.json', function (err, data) {
  if (err) throw err;
  t1 = JSON.parse(data);
});

update:

Like Nirk said, there is a synchronous version of fs.readFile. If you want to use that version, your code should look like:

t1 = JSON.parse(fs.readFileSync('./sample_data/t1.json'));
Answer:2

Is it possible to declare an anonymous generator function using the arrow syntax in ES6 JavaScript? This is what I've tried: let func = *() => { }; but this doesn't parse (I'm using Babel.js to ...

Is it possible to declare an anonymous generator function using the arrow syntax in ES6 JavaScript? This is what I've tried: let func = *() => { }; but this doesn't parse (I'm using Babel.js to ...

Title - Sorry about the title, it was difficult for me to actually explain this. So I recently finished working on a dynamic fields system using jQuery. This is all working great however I'm wanting ...

Title - Sorry about the title, it was difficult for me to actually explain this. So I recently finished working on a dynamic fields system using jQuery. This is all working great however I'm wanting ...

I was wondering if there was a feature or a way to select on line at a time from jquery/javascript. The issues is that it must be the element inside a <pre></pre> tags. The code look like ...

I was wondering if there was a feature or a way to select on line at a time from jquery/javascript. The issues is that it must be the element inside a <pre></pre> tags. The code look like ...

I Have four grids in Dojo, all of which update with real time data every few seconds. I only display one grid to the user at a time, but in the background all four grids update. This makes the page ...

I Have four grids in Dojo, all of which update with real time data every few seconds. I only display one grid to the user at a time, but in the background all four grids update. This makes the page ...