Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

135
Views
How do I run code before hoisted require statements?

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?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!