javascript - 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
解决方案
您正在导出一个函数,而不是一个带有函数的对象,并且您正在使用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')()
推荐阅读
- c# - 如何在.Net core 的测试中检查方法是否递归?
- c# - 等待异步下载完成
- python - CycleGAN - 工件和风格不转移
- php - 将 HTML 网页连接到 SQL Server
- vba - 使用带有标准列表和循环或循环的单独表优化 300 个附加查询
- java - 检查图像尺寸
- ruby-on-rails - Rails:在表单上使用 reCaptcha,用于传入参数的模型
- python - Pyomo:将结果保存到 CSV 文件
- java - 使用 Collections.unmodifiableMap 和 ConcurrentHashMap / HashMap 作为参数
- python - 如何定义矩阵的变量(不是数组)?归一化,Min_of_Matrix,Max_