0

I have the following piece of code in my "getpics.js" file:

var path = require('path');
var fs = require('fs');

const directoryPath = './public/img/slider'

exports.fileOnDisk = function(){
    fs.readdir(directoryPath, function (err, files) {
        //handling error
        if (err) {
            return console.log('Unable to scan directory: ' + err);
        };
        console.log(files);    
        return files;
    });

}

return module.exports;

here is my mail.js callup of the module:

var getpics = require('./public/js/slider/getpics.js');
getpics.fileOnDisk();

and this is the printout on the console:

[ 'next.png', 'next_hover.png', 'prev.png', 'prev_hover.png',
'slide1.jpg', 'slide2.jpg', 'slide3.jpg', 'slide4.jpg',
'slide5.jpg' ]

all good until now.

The question is why I cannot export the "files" outside this module, for example in a variable, to use them in my application?

FlaT
  • 99
  • 2
  • 10
  • Even if you did properly export the `filesOnDisk` function, it won't work as you expect it to. You need to first learn how to [return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call). – nicholaswmin Oct 27 '18 at 19:43

1 Answers1

1

The reason why you're unable to export those files directly is due to the async nature of NodeJS, specifically to the file system call fs.readdir. As that function call is processed in an asynchronous fashion, the code execution will proceed, and you won't be able to access whatever the result of that function is in order to export it. You can read more about it in the about section of NodeJS.

However, the NodeJS file system API does provide synchronous methods. Specifically to your case fs.readdirSync. Using that in your code you would end up with something like:

var path = require('path');
var fs = require('fs');

const directoryPath = './public/img/slider'

exports.fileOnDisk = fs.readdirSync(directoryPath, {encoding: 'utf8'})

You could then import this module and access the array of directories straight from fileOnDisk.

Be careful however as this code will be blocking.

João Antunes
  • 521
  • 4
  • 9