在我的node.js应用程序中,我让服务器从github获取原子提取,然后使用外部模块解析它。它在一个文件(getfeed.js)中工作正常但是当我将它导出到我的app.js文件并调用它时它返回undefined。当我在getfeed.js脚本中记录它时,它返回正确的数据;只是在app.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;
});
};
.
.
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 :(
});
.
.
.
.
.
答案 0 :(得分:3)
feedparser
是一个异步函数。您的getfeed
函数返回totalText,此时未定义。您需要将回调传递给getfeed
函数,并使用结果调用该回调。
<强> 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 :(
});