0

I have a frustrating issue happening right now. I'm trying to make a function that gets the files in a directory, but it just wont return the items.

function get_items(){
    fs.readdir(entire_path, function(err, items){
        console.log(items.join("\n"))
        return items.join("\n");
    });
}

console.log(get_items());

As you can see in this code, it console.logs the items, then returns the items, and then at the bottom it console.logs the output of the function. The console.log in the function works, but the second one does not. Why is this happening? This only happens in a function as well.

EDIT 1
Please don't mark as duplicate, I don't want to do

get_items(function(){
//do stuff
});

I want to be able to just do get_items();

EDIT 2
I used readdirSync instead.

Amateurz
  • 25
  • 5
  • readdir is async – marekful Jan 05 '18 at 05:33
  • This is a very popular question. See the duplicate for more info. You may have to dig into the answers a bit to find what applies best for you. But the concept is the same. You cannot return from within a callback. – elclanrs Jan 05 '18 at 05:33
  • Please read my edit, I know that it has asynchronous nature but thats not how I want this function executed. – Amateurz Jan 05 '18 at 05:37
  • If you don't want to use a callback, you can use `readdirSync`. But best advice is to learn how to handle async in JS. – elclanrs Jan 05 '18 at 05:37
  • I have tried readdirSync but it didn't return anything @elclanrs (as in it wouldnt even console.log the items) – Amateurz Jan 05 '18 at 05:39
  • Can you add the code for how you are using `readdirSync`? – elclanrs Jan 05 '18 at 05:42

0 Answers0