简体   繁体   中英

Require in global scope or local scope?

What is the correct way to require a node module? Is it more accurate/understandable to declare the module in the global scope, or is it more accurate/understandable to declare the module in the local scope?

For example, which of these makes the most sense:

Global:

let dns = require('dns') // <-- Global scope declaration
function lookup(subdomain, domain){
    let fqdn
    if(subdomain == '@'){
        fqdn = domain
    } else {
        fqdn = `${subdomain}.${domain}`
    }
    dns.resolveTxt(fqdn, (err, records) => {
        if(records){
            console.log(records)
        } else {
            console.log("no recrods")
        }
    })
}

Local:

function lookup(subdomain, domain){
    let dns = require('dns') // <-- Local scope declaration
    let fqdn
    if(subdomain == '@'){
        fqdn = domain
    } else {
        fqdn = `${subdomain}.${domain}`
    }
    dns.resolveTxt(fqdn, (err, records) => {
        if(records){
            console.log(records)
        } else {
            console.log("no recrods")
        }
    })
}

Is it a matter of opinion? If so, my apologies and I will delete the question.

I am looking to improve my code so others can more easily understand it, and I think this question is relevant to that purpose, so it shouldn't be considered an opinionated question.

First, a minor correction. Your first example is not global scope. That's module scope. Module scope with the declaration located at the beginning of your module file is the preferred implementation for the following reasons:

  1. It loads at startup (see text below for why that's good).
  2. Locating all these at the beginning of your module file clearly states in the code what external module dependencies you have in a nice easy to see way which is useful for anyone coming back to this code in the future to do maintenance (including you).
  3. You only ever require() this module once in this module. While modules are cached, it's better to not be calling require() every time you want to reference it. Load it once and use that saved module reference.

About point 1 above, require() is blocking and synchronous and involves accessing the file system (the first time that file is loaded). You generally want to get all your require() operations done at server-startup so no blocking operations are happening while you are processing requests. And, if you get any errors from require() (such as a module install missing or version conflict or bad configuration or missing dependency or something like that), you also want those to happen at startup time, not later where they are quicker to see and easier to diagnose.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM