DEV Community

Cover image for Quick Tip: Checking if a file exists before requiring it, using node.js
Jonas Schumacher
Jonas Schumacher

Posted on

1

Quick Tip: Checking if a file exists before requiring it, using node.js

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')
Enter fullscreen mode Exit fullscreen mode

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') 
Enter fullscreen mode Exit fullscreen mode

Now, regardless of the environment this is run in, everything should work fine.

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay