A javascript code to load all .js files in a directory

Ok, so i want to load all js files in a directory ATM im using this:

GDT.loadJs(['mods/Onlineplay/Source/SourceOnline.js', "mods/OnlinePlay/Plugins"], ready, error);

Not sure if that would work. but i want it so i do not have to specify the .js file

Here is something to start with. Using the following function you could get an array containing the list of files contained in a folder. To filter out ā€œ*.jsā€ you need to apply your own checks.

function getFiles(folder){
    var outFiles    = [];
    var fs          = require('fs');
   
    if ( typeof fs == 'undefined'){
        return outFiles;
    }
    
    var dir     = folder;
    var files   = fs.readdirSync(dir);
    
    for(var i = 0; i < files.length; i++) {
        
        var f  = files[i];
        var fn = f.substring(f.lastIndexOf('/')+1);
        try{
            var stats = fs.statSync(dir+f);
            if (stats.isFile()) {
                outFiles.push(dir+f);
            }
        }
        catch(ex){
            // Handle error(s) here
        }
    }
    
    return outFiles;        
}

Call it like:

var myFiles  = getFiles('./mods/YourMod/YourFiles/');

And then (i.e.)

GDT.loadJs(myFiles, ready, error);
1 Like

Iā€™d rather you just specify your js files manually. We might disallow using ā€˜fsā€™ (as suggested by @alphabit) for security reasons so this might break your mod in the futureā€¦

1 Like

I wasnā€™t sure whether to post this code or not. It comes from a deprecated internal UL method, which we used in the early days for dynamically loading JS files (which we dropped later for obvious reasons).

I wasnā€™t aware that it will be disallowed in future. So I need to make sure that I donā€™t use it somewhere else in my other mods :wink:

1 Like

ok, i guess for now i will do it manually. @alphabit thanks anyway
This can be locked now

1 Like

Slightly off-topic, but what about mods that rely completely on fs? :open_mouth:

can you explain how you use it a bit better? Maybe we can provide ways to save/load from specific directories instead of exposing the whole of fs.

Well, take my save backing up mod as an example :wink:
Although I could just store the backups in the regular data store anyway just like most other mods do, but it would get unneccesarily largeā€¦

I guess we could provide a dedicated file storage api which could also integrate with steam cloud on the steam version.

2 Likes