Node.js导出的函数没有返回正确的数据

在我的node.js应用程序中,我有服务器从github获得一个atom feed,然后使用外部模块parsing它。 它在一个文件(getfeed.js)中工作正常,但是当我将其导出到我的app.js文件并调用它时,它返回undefined。 当我将它logging到getfeed.js脚本中时,它将返回正确的数据; 只是在app.js里面的数据是未定义的。 很奇怪。 这是有问题的代码:

getfeed.js

module.exports = function() { var FeedParser = require("feedparser") , request = require("request") , ejs = require("ejs") , fs = require("fs"); var templateString = fs.readFileSync("./views/feed.ejs", { encoding: "utf-8"}); var req = request("https://github.com/codecademy-beginners/text-adventure/commits/master.atom") , feedparser = new FeedParser(); . . . . var totalText; feedparser.on('error', function(error) { console.error("Oops. There was an error. Sorry!"); }); feedparser.on('readable', function() { var stream = this , meta = this.meta , itemData; totalText = ""; while (itemData = stream.read()) { //console.log("TITLE: " + item.title + "\n"); //console.log("DESCRIPTION: " + item.description + "\n"); //console.log(item); totalText += ejs.render(templateString, { item : itemData } ); } console.log(totalText); //This is all as expected return totalText; }); }; 

app.js

 . . var getFeed = require("./getfeed"); . . . . . app.get("/feed", function(req, res) { var data = getFeed(); console.log(data); //undefined var formattedData = "<!DOCTYPE html><html><head><title>Feed</title></head><body>" + data + "</body></html>"; //Not the prettiest thing, but it works fine res.send(formattedData); //Just prints undefined onto the screen :( }); . . . . . 

feedparser是一个asynchronous函数。 你的getfeed函数返回totalText,这个时候是不确定的。 您需要将callback传递给getfeed函数,并调用该callback和结果。

getfeed.js

 module.exports = function(callback) { 

然后在你的feedparser.on('可读') –

 var totalText = '' feedparser.on('readable', var stream = this , meta = this.meta , itemData; while (itemData = stream.read()) { totalText += ejs.render(templateString, { item : itemData } ); } }); feedparser.on('end', function() { callback(totalText); }); 

app.js –

 getFeed(function(data) { console.log(data); //undefined var formattedData = "<!DOCTYPE html><html><head><title>Feed</title></head><body>" + data + "</body></html>"; //Not the prettiest thing, but it works fine res.send(formattedData); //Just prints undefined onto the screen :( });