Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return an array from glob node js

The issue

I'm using the answer here Get all files recursively in directories NodejS however, when I assign it to a constant I'm trying to return the directories so I can have them available in an array, I have looked through globs documentation for an asnwer https://github.com/isaacs/node-glob, however I have had no successful results, I have tried using glob.end() and I have also console.log the folds variable below, I can see all the list of available methods and I have tried to use some of them with no success, does anyone know how to return the array like in the code example below? Thank you!

 const glob = require('glob');
 const src = 'assets';


function getFiles(err, res){
  if (err) {
   console.log('Error', err);
  } else {
  return res
  }
}

let folds =  glob(src + '/**/*', getFiles);
like image 910
hjm Avatar asked Jan 22 '26 22:01

hjm


1 Answers

I had the same problem.

glob() is asynchronous and that can make returning the end result somewhat complicated.

Use glob.sync() instead (where .sync stands for synchronous)

Example:

const files = glob.sync(src + '/**/*');
like image 152
jaroslawjanas Avatar answered Jan 25 '26 21:01

jaroslawjanas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!