Shadow4Kill
Shadow4Kill

Reputation: 178

How to export module asynchronously in nodejs

I cannot export a module that I wrote it myself in an asynchronous way.

const glob = require('glob');

var confFiles;

glob("conf/**/*.conf", function (er, files) {
    confFiles = files;
});

module.exports = new Promise(function(resolve, reject) {
    resolve(confFiles);
});

This is the module itself and I want to access confFiles in other files but the point is that glob is not asynchronous and I'm having trouble finding my way to solve it.

Upvotes: 0

Views: 394

Answers (2)

nicholaswmin
nicholaswmin

Reputation: 22949

I'd export a load method instead:

// conf.js
const glob = require('glob')

module.exports.load = () => new Promise((resolve, reject) => {
  glob('conf/**/*.conf', function (err, files) {
    if (err) return reject(err)

    resolve(files)
  })
})

And then in userland:

// index.js
const conf = require('./conf.js')

conf.load()
  .then(files => {
    console.log(files)
  })

Or, you can just use globe.sync instead and avoid dealing with async code entirely:

// conf.js
const glob = require('glob')

module.exports = glob.sync('conf/**/*.conf')

And then in userland:

// index.js
const files = require('./conf.js')
console.log(files)

Just keep in mind that globe.sync is a blocking operation.

Upvotes: 0

Jonas Wilms
Jonas Wilms

Reputation: 138257

Resolve when the callback calls back:

module.exports = new Promise(function(resolve, reject) {
  glob("conf/**/*.conf", function (err, files) {
   if(err) reject(err) else resolve(files);
  });
}));

Or a bit shorter:

 const glob = require("glob");
 const { promisify } = require("util");

module.exports = promisify(glob)("conf/**/*.conf");

Upvotes: 1

Related Questions