NightScap3 NightScap3 - 4 months ago 10
Node.js Question

Using jsdom and update at every POST Request Variable with elements, but doesnt work

i have the problem, that my response function doesnt update the Variable, which takes an element out of an file:

Post Function:

app.post("/profile", function(req, res) {
var id = req.body.playerid;
request("https://statsroyale.com/profile/" + id).pipe(fs.createWriteStream('stats.html'));
var wins1 = document.getElementsByClassName('statistics__metricCounter ui__headerExtraSmall statistics__trophyMetric');
var wins = wins1[0].innerHTML;
res.render("profile", {person: id, wins: wins}); });


jsdom.env function(which sets the file onetime at the beginning):

jsdom.env({
file: 'stats.html',
done: function (err, window) {
GLOBAL.window = window;
GLOBAL.document = window.document;
}


});

But then, if i request an other id, it shows me the old element

Answer Source

Setting up your jsdom environment only occurs once. You'd need to use fs.watchFile() to keep track of any changes that occur to the file and re-initialize the environment each time that callback is invoked. In addition, you'll need to make sure that

var wins1 = document.getElementsByClassName('statistics__metricCounter ui__headerExtraSmall statistics__trophyMetric');
var wins = wins1[0].innerHTML;
res.render("profile", {person: id, wins: wins}); });

isn't invoked until after the asynchronous pipe completes and jsdom is re-initialized with the updated file.

Update

Even easier, instead of using a global dom initialized from the local HTML file, you can invoke jsdom directly from the URL:

jsdom.fromURL("https://statsroyale.com/profile/" + id, options).then(dom => {
  var wins1 = dom.window.document.getElementsByClassName('statistics__metricCounter ui__headerExtraSmall statistics__trophyMetric');
  var wins = wins1[0].innerHTML;
  res.render("profile", {person: id, wins: wins});
});