0

I am using glob to generate an array of filepaths. I can push those paths to a new array and log them from within the glob function; however, when I attempt to access the array outside the scope of the function, the array returns empty. Am I misunderstanding how to use glob? What might be the problem?

I've also tried returning the array and it is still empty. Additionally, I can't use ajax for this program.

Thanks!

var fs = require("fs");
var glob = require("glob");

let scssFiles = [];

glob("css/**/**/*.scss", "matchBase:true", function(er, files) {

    let file = '';

    for (let i = 0; i < files.length; i++) {
        file = files[i];

        scssFiles.push(file);
    }

    console.log(scssFiles);  // this works

});

console.log(scssFiles);  // returns empty array
lane
  • 659
  • 8
  • 24
  • I've tried returning the array and it is still empty. I can't use ajax for this program. – lane Jul 22 '19 at 13:54
  • 1
    Short answer - the second log will run before the glob returns. you have to stay in the context of the callback. If you switch to promises it's the same thing. You have to stay in context of when things run. Using `async/await` you can break out but then you are sidestepping understanding how to use async programming in js. – ktilcu Jul 22 '19 at 13:56
  • @ktilcu OK, are you saying that glob can/should surround the entire program? – lane Jul 22 '19 at 13:59
  • 1
    I'm not saying it's the best but it is what you would need to do here without switching to promises or async/await. The linked Q is really helpful. – ktilcu Jul 22 '19 at 14:04
  • 1
    @ktilcu I will read up on it. Thank you for helping me understand it better! – lane Jul 22 '19 at 14:05

0 Answers0