Luke D
Luke D

Reputation: 55

Node attempting to read file before synchronous write finishes

I am trying to make my program such that it will attempt to read a config file, and if the config file doesn't exist, the program will generate a new config file from config.example.js and then require the newly generated file. However, I am running into an issue - even with using fs.writeFileSync(), it appears that Node is running config = require('config.js'); before the "synchronous" write finishes, as it crashes with Cannot find module './config.js'.

Here is the code in question:

var config;
//Create new config file if one not found
try {
    config = require('./config.js');
} catch (e){
    fs.writeFileSync('./config.js', fs.readFileSync('./config.js.example'));
    console.log("New config file config.js created");
    config = require('./config.js');  //Line it crashes on
}

Upvotes: 1

Views: 57

Answers (1)

Jonathanfmills
Jonathanfmills

Reputation: 26

This is because of the way caching works with require. Because the first one failed, so will the second one until the event loop clears. Try it this way instead.

if (fs.existsSync('/config.js')) {
    config = require('./config');
} else {
    fs.writeFileSync('./config.js', fs.readFileSync('./config.js.example'));
    config = require('./config');
}

Upvotes: 1

Related Questions