0

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);
2
  • 1
    a) don't use the asynchronous version of readFile or b) log the imported values only after the file was read. Easiest when you export a promise for the values. Commented Nov 18, 2022 at 19:22
  • 2
    When you import from readCredentials.js, the fs is still in the process of reading the file. In your case fs.readFileSync is what you want. Commented Nov 18, 2022 at 19:22

2 Answers 2

3

In a CommonJS module, you cannot assign module.exports as the result of any asynchronous operation. This is because the whole loading process does not wait for your asynchronous operation to complete.

As such, the consumer of that export will be using its value BEFORE it has been assigned by your asynchronous operation.

In an ESM module and recent version of nodejs, you can use use top level await with promises to accomplish something like this.

But, since this is just part of the module loading process, you can just switch to synchronous I/O using fs.readFileSync() or just use require() which can load and parse .json files for you automatically and solve your problem that way.

const { username, password } = require("./config.json");
module.exports = { username, password };
Sign up to request clarification or add additional context in comments.

Comments

2

The easiest way out could be to use plain require instead (it can read and parse json files just fine). An alternative would be readFileSync, as above.

readCredentials.js

const config = require("./config.json");
const username = config.username;
const password = config.password;
console.log(username, password);
module.exports = { username, password };

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.