I want to generate a file at the beginning of my program. This must happen before the module is loaded, as the module will try to load that file.
Here is my code:
require('dotenv').config();
const fs = require('fs');
//if cert doesn't exist, create the file from an environment variable
if (!fs.existsSync('./ca-certificate.crt')) {
if (!process.env.MONGO_CERT) throw new Error('The mongo cert wasnt found as a file or in environment variables');
fs.writeFileSync('./ca-certificate.crt',process.env.MONGO_CERT);
console.log('wrote MONGO_CERT to file');
} else console.log('Mongo cert file detected');
const http = require('http');
const path = require('path');
const glob = require('glob');
const cookieParser = require('cookie-parser');
const busboy = require('express-busboy');
const express = require('express');
const morgan = require('morgan');
const queue = require('./queue.js');
and queue.js
require('dotenv').config();
const {MongoClient, Collection} = require('mongodb');
const client = new MongoClient(process.env.MONGO_URI);
The problem is the app crashes in module.js due to not being able to find the file. I believe this to be due to node hoisting the module definition to before my if statement, so that whole module is getting run before even getting to my code.
How do I prevent this?