Quick tips are small snippets that come up again and again in my work, for which I want a permantent and central place to retrieve them.
Here's the situation: You want to require()
a .json
file that might or might not yet exist.
const jsonContent = require('path/to/fileThatMightNotExist.json')
If it exists, this will work fine, if it doesn't, this will blow up. To make sure that is exists before you load it up, simply add the following:
const fs = require('fs')
if (!fs.existsSync('path/to/fileThatMightNotExist.json')) {
fs.writeFileSync('path/to/fileThatMightNotExist.json', JSON.stringify({}))
}
// now exists, despite the name
const jsonContent = require('path/to/fileThatMightNotExist.json')
Now, regardless of the environment this is run in, everything should work fine.
Top comments (0)