[英]How to check if module function exist in Node js
I have created a module and defined functions in it. 我已经创建了一个模块并在其中定义了功能。 Sometimes I need to check if a certain function is actually already created.
有时我需要检查某个功能是否已经实际创建。
For example 例如
var newyork = function() {
console.log("newyork");
};
var washington = function() {
console.log("washington");
};
exports.newyork = newyork;
exports.washington = washington;
Now in the different file, I want to first check if the function exists, something like: 现在在另一个文件中,我想首先检查该函数是否存在,例如:
var cities = require('./city');
if(cities.newyork) {
console.log("city function exist");
}
else {
//false
}
As I said in the comments what you wrote actually works because 正如我在评论中所说,您写的内容实际上是有效的,因为
if(cities.newyork){
Checks if cities.newyork
is truthy . 检查
cities.newyork
是否真实 。 The following things are truthy: 以下内容是真实的:
If it is however not defined, cities.newyork
will be undefined
which is falsy (will enter the else
branch) 如果然而没有定义,
cities.newyork
将undefined
这是falsy(将进入else
分支)
typeof cities.cityName === 'function'
typeofities.cityName ==='功能'
if city's name is assigned to some variable 如果城市名称已分配给某个变量
typeof cities[cityName] === 'function'
类型的城市[cityName] ==='功能'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.