I am using fs.readFile to read the content of config.json in readCredentials.js. Then I am exporting the function so I can use it it config.js.
When I run node config.js I get two undefined and then real values of username and password in config.js. Any idea how i can fix this?
readCredentials.js
const fs = require("fs");
fs.readFile("./config.json", (err, data) => {
if (err) {
console.log(err);
}
const config = JSON.parse(data);
const username = config.username;
const password = config.password;
console.log(username, password);
module.exports = { username, password };
});
config.json
{ "username": "xyz", "password": "xyz" }
config.js
const { username, password } = require("./readCredentials.js");
const usernameValue = username;
const passwordValue = password;
console.log(usernameValue, passwordValue);
readFileor b) log the imported values only after the file was read. Easiest when you export a promise for the values.readCredentials.js, thefsis still in the process of reading the file. In your casefs.readFileSyncis what you want.