首页 > 解决方案 > 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

标签: javascriptnode.jsundefined

解决方案


您正在导出一个函数,而不是一个带有函数的对象,并且您正在使用console.log带有异步操作的同步函数 ().. 它不起作用。

你需要这样写:

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}) })

记住以下之间的区别:

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

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

推荐阅读