Search code examples
node.jsexpresscommonjs

creating a base file for modules to use in other files


in our express application we are using same modules over and over for our controller files , is there a good way to have one file and require all needed modules there, and only require that one file in controller files ? so far i have tried this :

baseFile.js

const appDir = process.env.PWD
const co = require('co');
const db = require(appDir+'/model')
const helper = require(appDir+'/controller/helper')
module.exports = {
    co : co ,
    db : db,
    helper : helper
}

ohterFile.js

let base = require(process.env.PWD+'/components/controller')

base.db.User ...

but as you can see this is not ideal because we don't have straight access to co and db modules, we need to do base.db instead of just db
is there anyway to require them in a way so we have straight access to each module ? note : our node version is old and not supporting import/export


Solution

  • so thanks to @Prakash sharma I finally made it using object destructi

    const appDir = process.env.PWD
    const co = require('co');
    const db = require(appDir+'/model')
    const helper = require(appDir+'/controller/helper')
    const express = require('express')
    const firebase = require(appDir+'/controller/firebase')
    const config = require(appDir+'/Config.js')
    
    module.exports = {
        co : co ,
        db : db,
        express : express ,
        firebase : firebase,
        config : config
    }
    

    and in other files i use it like this :

    const appDir = process.env.PWD
    const {co,db,helper,express,firebase} = require(appDir+'/components/modules')