How to check if path of file exist


Hi, I am new to vue. I am importing a json file dynamically like this:

this.storyToRead = require('../assets/data/stories/' + this.storyFileName)

if the file is found, I place the data in store. All work fine but sometimes the file doesn’t exist (I am testing edge cases) and I get an ‘Uncaught Error: Cannot find module’, in console.

I would like to create a warning if the path to the file (or the file) doesn’t exist. Basically I would like to do something like:

if ( !require('../assets/data/stories/' + this.storyFileName)) {
  // do something

obviously this doesn’t work, but is there anything I can do to achieve the same result?


You can’t really. require isn’t a native javascript function, it’s a webpack function to import modules. So, the file must be available when you build out the app with webpack.

A better strategy would be to request the file with an XHR and handle the success/error of the request.


Thank you. I handled the issue with ‘try catch’:

try {
  this.storyToRead = require('../assets/data/stories/' + this.storyFileName)
  // do something
} catch (e) {
  // do something else