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

131
Views
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 answers
Answer question

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 Report

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 Report

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 Report
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!