0

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.

Shadow4Kill
  • 178
  • 1
  • 9

2 Answers2

1

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");
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
0

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.

nicholaswmin
  • 21,686
  • 15
  • 91
  • 167