javascript - 需要在全局范围内还是在本地范围内?
问题描述
要求节点模块的正确方法是什么?在全局范围内声明模块更准确/更易于理解,还是在本地范围内声明模块更准确/更易于理解?
例如,以下哪个最有意义:
全球的:
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")
}
})
}
这是意见问题吗?如果是这样,我很抱歉,我会删除这个问题。
我希望改进我的代码,以便其他人更容易理解它,我认为这个问题与该目的相关,因此不应将其视为一个固执己见的问题。
解决方案
首先,小幅修正。您的第一个示例不是全局范围。那是模块范围。声明位于模块文件开头的模块范围是首选实现,原因如下:
- It loads at startup (see text below for why that's good).
- 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).
- You only ever
require()
this module once in this module. While modules are cached, it's better to not be callingrequire()
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.
推荐阅读
- python - 我正在尝试在同一图中绘制不同温度的黑体?
- javascript - 模板未显示在我的 Laravel 6.6 项目中使用 Vue.js
- c# - Java.Lang.IllegalArgumentException:无效位图格式在启动时间歇性
- vue.js - 将 Flask 与 Nuxtjs 结合用于 SSR
- mysql - 如何在 MySQL 中使用 insert 和 update 执行 case 语句?
- sql - 使用查询中的值更新表中的字段
- java - 用 rbf 核计算 svm 的 w 向量
- regex - Notepad++ 中的正则表达式用于选择特定 XML 标记之间的字符串长度
- databricks - 我的文件系统名称和存储帐户名称是什么?我如何找到它?
- python - Tensorboard (PyTorch) add_graph 中的错误