无法从nodejs中的另一个js文件导出对象

Unable to export object from another js file in nodejs

本文关键字:文件 js 对象 另一个 nodejs      更新时间:2023-09-26

我正在尝试使用getCurrentSongData函数来返回从scraper传入的songdata对象,但我一直得到这样的输出:

******************TESTING****************
c:'Users'(PATH TO PROJECT FOLDER)'node_modules'mysql'lib'protocol'Parser.js:82
        throw err;
        ^
TypeError: Cannot read property 'artist' of undefined
    at getCurrentSongData 
...

这是routes.js文件中需要scraper的部分。

function getCurrentSongData(un) {
    var scraper = require('./scrape');
    console.log("******************TESTING****************");
    console.log("testfunct: " + scraper(un).artist);
         return scraper(un);
}

这是刮刀

您在scrape.js中发出异步请求,因此需要使用返回提取的歌曲数据的回调,否则会得到undefined,因为module.exports函数没有返回任何内容。

function getCurrentSongData(un) {
  var scraper = require('./scrape');
  scraper(un, dataLoaded);
}
function dataLoaded(songData) {
  console.log(songData.artist);
}