简体   繁体   中英

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 . The following things are truthy:

  • functions (thats why it works here)
  • numbers except 0
  • strings except an empty one
  • objects / arrays

If it is however not defined, cities.newyork will be undefined which is falsy (will enter the else branch)

typeof cities.cityName === 'function'

if city's name is assigned to some variable

typeof cities[cityName] === 'function'

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