首页 > 解决方案 > 需要在全局范围内还是在本地范围内?

问题描述

要求节点模块的正确方法是什么?在全局范围内声明模块更准确/更易于理解,还是在本地范围内声明模块更准确/更易于理解?

例如,以下哪个最有意义:

全球的:

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")
        }
    })
}

当地的:

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")
        }
    })
}

这是意见问题吗?如果是这样,我很抱歉,我会删除这个问题。

我希望改进我的代码,以便其他人更容易理解它,我认为这个问题与该目的相关,因此不应将其视为一个固执己见的问题。

标签: javascriptnode.jsmodulescope

解决方案


首先,小幅修正。您的第一个示例不是全局范围。那是模块范围。声明位于模块文件开头的模块范围是首选实现,原因如下:

  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.


推荐阅读