简体   繁体   English

未定义的 var module.exports

[英]undefined var module.exports

For some reason, I can't get values returned from module.exports function from a separate custom module.出于某种原因,我无法从单独的自定义模块中获取从 module.exports function 返回的值。 I tried many ways from many sources from >10s researched posts.我从超过 10 个研究帖子的许多来源尝试了许多方法。 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 //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 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM