Node.js Fs create file if doesn't exist

Viewed 2656

Not sure why this is not working, I have looked through the similar threads already but can't get around this. I'm trying to check if a file (config.json) exists and if it doesn't create it.

Code:

try {
  if (fs.existsSync('./config.json')) {
    //config.json exists
  }
} catch(err) {
    fs.writeFile('config.json', configTemplate, function (err) {
      if (err) throw err;
      console.log('File is created successfully.');
    });
}

This gives me the following error in the console and doesn't create the file:

fs.js:114
    throw err;
    ^

Error: ENOENT: no such file or directory, open './config.json'

Thanks for any input on this!

0 Answers
Related