0

Bit of context: I am learning nodejs/express and have got a small application that in the end should function as an api. I have got a routes directory with a few subdirectories containing files such as Post.js or Users.js, each file defining a few routes for Posts, Users etc.

I have the following bit of code in my index.js placed in routes directly:

public readDir(path, app) {
    let dir = path != null ? path : __dirname;
    fs.readdir(dir, (err, elements) => {
        if(err) throw err;
        if(!elements) return;
        elements.forEach(element => {
            if(element === "init.js") return;
            let new_path = x.join(dir, "/", element);
            fs.lstat(new_path , (err, stat) => {
                if(err) throw err;
                if(stat.isDirectory()) {
                    this.readDir(new_path , app);
                } else if(stat.isFile()) {
                    require(PATH)(app);
                }
            });
        });
    });
}

What it does is the following: It reads the Routes directory with each subdirectory by calling itself in a loop and requiring any file that is found (path module is imported as x, I should probably change that sometime). This works fortunately, every route is mapped properly and can be accessed by making a call with postman / insomnia.

My question would be how this could be done better, primarily performance wise whilst still keeping the structure of multiple files and/or directories?

I have already seen this answer and this one and though both seem like great and functional answers I was wondering which would be the better option?

Any pointers would be great!

Storm Epke
  • 93
  • 9
  • If this is working code and you just want to solicit improvements, I'd suggest http://codereview.stackexchange.com. Please read their posting rules as to the format of questions there before posting. – jfriend00 Nov 04 '19 at 22:50
  • Why do you care at all about performance of this code? Isn't this server startup code? – jfriend00 Nov 04 '19 at 22:52
  • FYI, `if (err) throw err` is worthless error handling in async code. It does absolutely nothing useful. Your whole design has no ability to communicate back to the caller either completion or errors and has no strategy for what to do if there's an error other than just throw up your hands and throw asynchronously which can't be caught by any caller. – jfriend00 Nov 04 '19 at 22:53
  • @jfriend00 Now that you mention it, it is indeed startup code so I shouldn't really mind performance I suppose and my apologies for getting the wrong overflow site. Thanks for pointing out the `if (err) throw err` statement, i'll revise them. Cheers! – Storm Epke Nov 05 '19 at 07:19

0 Answers0