Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

132
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda