Reputation: 6086
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
Upvotes: 2
Views: 1753
Reputation: 4795
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'));
Upvotes: 4
Reputation: 888185
Your suspicion is correct.
require()
caches modules; it will only read each file from disk once.
You can break this cache like this:
delete require.cache[require.resolve('...')];
Alternatively, you can read the file yourself using the fs
module, then call JSON.parse()
.
Make sure to correctly pass a relative or absolute path (you may want to call require.resolve()
).
Upvotes: 2