DEV Community 👩‍💻👨‍💻

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

Posted on

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)

Classic DEV Post from 2020:

js visualized

🚀⚙️ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! 🥳

Happy coding!