出于某种原因,我无法从单独的自定义模块中获取从 module.exports 函数返回的值。我从超过 10 篇研究帖子的许多来源中尝试了很多方法。如果您想投反对票,请阅读我的简历,或者如果您想提供帮助,我很乐意接受您的回答。
//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
最佳答案
您正在导出函数,而不是具有函数的对象,并且您正在使用同步函数 (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')()
关于javascript - 未定义的 var module.exports,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58542134/