Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

136
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda