Home > Back-end >  module.exports returns undefined in Node JS
module.exports returns undefined in Node JS

Time:11-19

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);

CodePudding user response:

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 };

CodePudding user response:

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 };
  • Related