在带有元素的每个 POST 请求变量处使用 jsdom 和更新,但不起作用

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

我有问题,我的响应函数没有更新变量,它从文件中取出一个元素:

Post 函数:

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 函数(在开头设置文件一次):

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

});

但是,如果我请求另一个 ID,它会显示旧元素

源代码:

 var express = require("express");
var app = express();
var bodyParser = require('body-parser')
var request = require("request")
var fs = require("fs");
var $ = require("jquery");
var jsdom
try {
  jsdom = require("jsdom/lib/old-api.js"); // jsdom >= 10.x
  const { JSDOM } = jsdom;
} catch (e) {
  jsdom = require("jsdom"); // jsdom <= 9.x
  const { JSDOM } = jsdom;
}
app.use( bodyParser.json() );
app.use(bodyParser.urlencoded({
  extended: true
}));
app.set("view engine", "ejs");
app.get("/", function(req, res) {
    res.render("home");
});
app.post("/profile", function(req, res) {
    var id = req.body.playerid;
    jsdom.JSDOM.fromURL("https://statsroyale.com/profile/" + id).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});
    });
});
app.get("/profile", function(req, res) {
    var id = req.query.playerid;
    res.render("profile", {person: id});
});
app.listen(3000);

设置您的 jsdom 环境只需要一次。您需要使用 fs.watchFile() 来跟踪文件发生的任何更改,并在每次调用回调时重新初始化环境。此外,您需要确保

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

直到异步 pipe 完成并且 jsdom 使用更新的文件重新初始化后才会被调用。

更新

更简单,而不是使用从本地 HTML 文件初始化的全局 domyou can invoke jsdom directly from the URL:

jsdom.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});
});