Best approach to passing variables between files with multiple Node.js files?

I have a Node.js module that I saved as a single file until now. It becomes quite large and has a lot of functionality that can be better divided into other modules. For example, separating logging initialization and functionality in its own module.

In my module there are many (I want to say "global", but not real) top-level variables, access to which, use and modification of many different functions. If I split functionality into separate files / modules and require them in my main module, what is the correct approach to transfer these variables between modules?

For example, with everything in one module / file this is easy to do:

const logger = (log, message) {........}

const makeRequestHandler = (url, filepath) {
    ....
    logger.info('some message here')
    ....
}

So it's pretty easy to access top-level systems such as logger. But if I decided to share my loggerand makeRequestHandleron their own modules / files, how would I handle this?

let logger = require('./mylogger') // Custom module
let makeRequest = require('./makerequest') // Another custom module

makeRequest.handler(url, filepath, logger)

It will work, but it does not seem elegant or optimal. It would be even weirder if I had many different variables that I needed to go through:

makeRequest.handler(url, filepath, logger, profiler, reportingBuffer, compressionHandler)

I also considered transferring materials to modules as needed:

let makeRequest = require('./makeRequest')(logger)

or better yet:

let makeRequest = require('./makeRequest')(this) // I can access all variables made in my primary/top-level module

Is there an approach that is more suitable and better / easier to maintain? Is the last best approach?

+4
source share
1 answer

/ , , - , .

, , , , this .

//logger.js
const logger = (log, message) {........}
export logger

 let logger = require('./mylogger') // Custom module
 init() {
    //init and set the logger 
    global.logger = new logger();
    ...
 }

makRequest

  let logger = global.logger;
    const makeRequestHandler = (url, filepath) {
        ....
        logger.info('some message here')
        ....
    }

, :

//Solution 1 : As you pointed out yourself this can get messy when number of paramters increase and is not very readable or understandable.
let logger = require('./mylogger') 
let makeRequest = require('./makerequest') 
makeRequest.handler(url, filepath, logger)


//Solution 2 : Passing around the `this` context is never a good idea,for keeping sensitive data independent or scope isolation
let makeRequest = require('./makeRequest')(this)

: . npm, , Service Locator ,

0

Source: https://habr.com/ru/post/1695614/


All Articles