I literally just started nodeJS and have been meddling with it for the past 8 hours. I have done J2EE and .NET before and wanted to get into NodeJS too.
I faced a problem while trying to get the response from the Data.js file. I can successfully stringify the data but for some reason I can't return it back. It ends up being null or and empty string(its default value) in the index.js router. I have explained with comments in the Data.js code below.
Thank you in advance and please tell me how I can improve my code :) I still have lots of concepts to learn
index.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
var Data = require('../public/javascripts/Data');
var responseString = Data.test;
res.render('index', { d: responseString });
console.log(responseString)
});
module.exports = router;
Data.js
var request = require('request'),
cheerio = require('cheerio'),
responseTitles = [],
responseUrls = [],
responseJSONArray = [],
responseTotalNumber = 0,
responseString = "";
function getData(){
request('URL',function(err,response,body){
console.log("requesting..")
if(!err && response.statusCode == 200){
console.log("success..")
var $ = cheerio.load(body);
var data = [];
data = $('span.titletext');
data.each(function(i){
responseTitles.push(data[i].children[0].data);
responseUrls.push(data[i].parent.attribs.url);
responseTotalNumber = i;
responseJSONArray.push([{index: i, Title: data[i].children[0].data, url: data[i].parent.attribs.url}])
});
responseString = JSON.stringify(responseJSONArray);
//At this point, responseString has all the data but
//if I put the return here, it doesn't return anything
}
});
//At this point responseString returns "". And so it returns an empty string
return responseString;
}
module.exports= {
test: getData()
};