在 NodeJS 的构造函数中使用 `require` 是一种不好的做法吗?
Is it a bad practice to use `require` inside a constructor in NodeJS?
我正在构建一个需要特定单词列表的节点应用程序。单词表位于 JSON 文件中,看起来像这样:
{
"en":["foo", "bar"],
"gr": ["foo", "bar"]
}
JSON 文件中的每个键代表一种不同的语言。
用户在创建对象时必须选择一种语言。所以我正在考虑像这样在构造函数中导入 JSON 文件:
const list = require('./config/lang.json')[lang]
其中 lang 是传递给构造函数的参数。
这是不好的做法吗?
我听说有人说您应该始终在代码的开头使用 require
。我是否应该只在代码 const list = require('./config/lang.json')
的开头要求全部内容,然后在构造函数中仅提取所需的语言 const wordlist = list[lang]
?
即使代码工作相同,并且 require
调用被缓存。在您的情况下,不需要在每个新实例上都调用额外的函数,因此执行以下操作会更快(在这种情况下并不重要):
const langs = require('./config/lang.json');
class MyClass {
constructor(lang) {
const list = langs[lang];
}
}
另外需要注意的是,require
是同步的,所以如果你的JSON特别大,第一次实例化MyClass
事件循环会被阻塞。在一开始就使用它,它可能会在服务器(或您正在做的任何事情)启动之前加载,因此 require
花费一些时间不会有问题。
所以,是的,在我看来,require
调用应该在顶部,除非您知道自己在做什么,或者您正在加载动态依赖项。
Is this a bad practice?
不完全是,require
有缓存所以没关系。
I've heard people say that you should always use require in the beginning of your code.
是的,这是一种很好的做法,可以轻松发现依赖项。
Should I just require the whole thing in the beginning of my code const list = require('./config/lang.json')
and then simply extract only the required language const wordlist = list[lang]
inside of the constructor?
是的,我会那样做。如果它是动态依赖项,我只会将 require
放入构造函数中,例如 const wordlist = require(
./config/lang/${lang}.json)
.
我正在构建一个需要特定单词列表的节点应用程序。单词表位于 JSON 文件中,看起来像这样:
{
"en":["foo", "bar"],
"gr": ["foo", "bar"]
}
JSON 文件中的每个键代表一种不同的语言。
用户在创建对象时必须选择一种语言。所以我正在考虑像这样在构造函数中导入 JSON 文件:
const list = require('./config/lang.json')[lang]
其中 lang 是传递给构造函数的参数。
这是不好的做法吗?
我听说有人说您应该始终在代码的开头使用 require
。我是否应该只在代码 const list = require('./config/lang.json')
的开头要求全部内容,然后在构造函数中仅提取所需的语言 const wordlist = list[lang]
?
即使代码工作相同,并且 require
调用被缓存。在您的情况下,不需要在每个新实例上都调用额外的函数,因此执行以下操作会更快(在这种情况下并不重要):
const langs = require('./config/lang.json');
class MyClass {
constructor(lang) {
const list = langs[lang];
}
}
另外需要注意的是,require
是同步的,所以如果你的JSON特别大,第一次实例化MyClass
事件循环会被阻塞。在一开始就使用它,它可能会在服务器(或您正在做的任何事情)启动之前加载,因此 require
花费一些时间不会有问题。
所以,是的,在我看来,require
调用应该在顶部,除非您知道自己在做什么,或者您正在加载动态依赖项。
Is this a bad practice?
不完全是,require
有缓存所以没关系。
I've heard people say that you should always use require in the beginning of your code.
是的,这是一种很好的做法,可以轻松发现依赖项。
Should I just require the whole thing in the beginning of my code
const list = require('./config/lang.json')
and then simply extract only the required languageconst wordlist = list[lang]
inside of the constructor?
是的,我会那样做。如果它是动态依赖项,我只会将 require
放入构造函数中,例如 const wordlist = require(
./config/lang/${lang}.json)
.