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

130
Vistas
Unable to export db properties from nodejs module

I am trying to export database properties stored in properties file from Javascript module. By the time I read database properties file, Javascript file is already exported and data properties appear undefined wherever I use in other modules.

const Pool = require('pg').Pool;
const fs = require('fs')
const path = require('path');

class DbConfig {
    constructor(dbData) {
        this.pool = new Pool({
            user: dbData['user'],
            host: dbData['host'],
            database: dbData['database'],
            password: dbData['password'],
            max: 20,
            port: 5432
        });
    }
}

function getdbconf() {
    const dbData = {};
    fs.readFile("../../db_properties.txt"), 'utf8', (err, data) => {
        if (err) {
            console.error(err)
            return
        }
        // dbData = {"user":"postgres", "password": "1234"...};
        return dbData;
    });
}
    

let db = new DbConfig(getdbconf());
let dbPool = db.pool;
console.log("dbpool : -> : ",dbPool); // username and password appear undefined
module.exports = { dbPool };

Is there a way to read data before exporting data from Javascript module?

about 4 years ago · Santiago Gelvez
3 Respuestas
Responde la pregunta

0

Usually database config or any other sensitive info is read from a .env file using dotenv .

Or

you could also provide env from command line itself like

DB_HOST=127.0.0.1 node index.js

inside your index.js

console.log(process.env.DB_HOST)
about 4 years ago · Santiago Gelvez Denunciar

0

Exporting the result of async calls

To export values which have been obtained asynchronously, export a Promise.

const fs = require('fs/promises'); // `/promise` means no callbacks, Promise returned

const dbDataPromise = fs.readFile('fileToRead')); //`readFile` returns Promise now

module.exports = dbDataPromise;

Importing

When you need to use the value,

const dbDataPromise = require('./dbdata');


async init() {
  const dbData = await dbDataPromise;
}

//or without async, using Promise callbacks
init() {
  dbDataPromise
    .then(dbData => the rest of your code that depends on dbData here);
}

Current code broken

Please note that your current code, as pasted above, is broken:

function getdbconf() {
    const dbData = {};
    fs.readFile("../../db_properties.txt"), 'utf8', (err, data) => {
        //[...] snipped for brevity 
        return dbData;
    });
}

fs.readFile "returns" dbData, but there is nothing to return to, since you are in a callback which you did not call yourself. Function getdbconf returns nothing.

The line that says let db = new DbConfig(getdbconf()); will NOT work. It needs to be inside the callback.

The only way to avoid putting all of your code inside the callback (and "flatten" it) is to use await, or to use readFileSync

Avoiding the issue

Using environment variables

Suhas Nama's suggestion is a good one, and is common practice. Try putting the values you need in environment variables.

Using synchronous readFile

While using synchronous calls does block the event loop, it's ok to do during initialization, before your app is up and running.

This avoids the problem of having everything in a callback or having to export Promises, and is often the best solution.

about 4 years ago · Santiago Gelvez Denunciar

0

Please create a new file (connection-pool.js) and paste this code:

const { Pool } = require('pg');

const poolConnection = new Pool({
  user: 'postgresUserName',
  host: 'yourHost',
  database: 'someNameDataBase',
  password: 'postgresUserPassword',
  port: 5432,
});

console.log('connectionOptions', poolConnection.options);

module.exports = poolConnection;

For use it, create a new file (demo-connection.js) and paste this code:

const pool = require('./connection-pool');

pool.query('SELECT NOW();', (err, res) => {

    if (err) {
        // throw err;
        console.log('connection error');
        return;
    }

    if (res) {
        console.log(res.rows);
        pool.end();
    }
});

This is an alternative option 🙂

about 4 years ago · Santiago Gelvez Denunciar
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