简体   繁体   中英

undefined var module.exports

For some reason, I can't get values returned from module.exports function from a separate custom module. I tried many ways from many sources from >10s researched posts. If you want to vote down, please read my bio or if you want to help I will be happy to accept your answer.

// restapi/index.js

module.exports = function gifs() {

    giphy.search('Pokemon', function (err, res) {
        return res.data[0];
    });
}

// main server.js

var readapi = require('restapi')
console.log(readapi.gifs());

// Output:__________________

TypeError: readapi.gifs is not a function

You are exporting a function, not an object with a function and you are using a sync function ( console.log ) with an async operation.. it won't work.

You need to write it like this:

module.exports = function gifs(cb) {
  giphy.search('Pokemon', function (err, res) {
    if(err) { cb(err) }
    else { cb(null, res.data[0]) }
  });
}

----

var readapi = require('restapi')
readapi((err, data) => { console.log({err, data}) })

Remember the difference between:

module.export = {
  hello: () => { console.log('world') }
}
// usage: require('./hello').hello()

module.export = () => { console.log('world') }
// usage: require('./hello')()

Try this code

module.exports.gifs = function gifs() {
    return new Promise((resolve, reject) => {
      giphy.search('Pokemon', function (err, res) {
         if (err) reject(err);
         else resolve(res.data[0]);
      });
    });
}

// main server.js

var readapi = require('restapi')
readapi.gifs().then(console.log);

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