简体   繁体   中英

export module in node.js

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM