0

When working in NodeJS and requiring custom modules. Is it best practice to require one file that itself requires dependencies, or is it best to explicitly require only the files that are needed?

An example might be having a database class that returns a connection pool. db_conn.js

Then there might be separate files that export methods for saving different types of models. e.g

 db_user.js
 db_blog_post.js

Each of these files need to require('db_conn.js') in order to get a pool

But then in the main app is it best to explicitly require('db_user') or is it better to create an index.js file in a 'db' folder that itself requires db_user and db_blog_post exporting references to them?

e.g

  let blog = require('db_blog_post')
  let user = require('db_user')

  module.exports.user = user
  module.exports.blog = blog

and then in a router just require this whole file

 let db = require('db')

 db.user.save({"some":"value"})
 db.blog.save({"some":"value"})

Or should the router only require what it needs. e.g if it only interacts with blogs

let db_blog = require('db_blog_post')

db_blog.save({"some":"value"})
// but can't do anything with a user here.

Or actually is it best to just create Model classes that have appropriate methods such as making use of ES6 classes?

 save()
 delete()
 etc...

I know this seems to be the case with Mongoose but I'm looking at this from a mysql perspective.

Thanks

1

As usual, it depends. I generally have a folder of related things (e.g. controllers) which includes an index.js file. That file exports an object of all the other files in the same folder, e.g.:

module.exports = { users : require('./users') }

This lets me require the folder itself elsewhere but also do a specific require if I want.

I don't think there is an objective "best" here, it comes down to how you like to organize stuff and whether you often use multiple files of the same type in one place.

So for example, I often have one file that configures all my routes, so in there it makes sense to require the whole controllers folder and call them like your DB example. I rarely have more than one Model being used in the same file, though, so it's less useful to do it that way.

Also, it should be noted that your example is a bad one. If you call module.exports = twice in the same file, you will overwrite the first with the second, as it's a property assignment.

  • Thanks for the response. I don’t overwrite module.exports in my example though I was setting individual properties on it such as .user and .blog. I guess it will just come down to how I want to organise things as you say – TommyBs Oct 20 '17 at 14:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.