node.jsparsinghtml文本以获得一个javascriptvariables的值

我成功地做到这一点,以获得我感兴趣的页面的帮助文本。

router.get('/get', function (req, res) { var pg = 'https://j......com/f/resource' console.log('get', pg); requestify.get(pg).then(function (resp) { console.log(resp.body); }); }); 

现在,我有页面的文本,我想parsing文本来获取我知道存在于文本中的JavaScriptvariables的值。

 <script> var x1 = {"p": {.......bla bla ...}};</script> 

我知道有时<script>标签将包含type属性; 但并不总是包含type属性。

当我findx1的值时,我在javascript的应用程序中将myVarvariables中的值用于什么目的。

如果你没有答案,那么你对我应该研究什么的评论/提示是值得赞赏的。

我希望我会find一些模块,我可以把整个文本,并有模块以某种方式只是输出所有variables为我的值。

所以你没有重新发明轮子,我觉得使用JSDOM (它的执行能力)将是最好的。 嘲笑你有什么:

 const express = require('express'); const jsdom = require("jsdom"); const { JSDOM } = jsdom; // it exports a JSDOM class // Mock a remote resource const remote = express() .use('/', (req, res) => { res.send('<!DOCTYPE html><html lang="en-US"><head><title>Test document</title><script>var x1 = { "p": { "foo": "bar" } };</script></head><body></body></html>'); }) .listen(3001); // Create "your" server const local = express() .use('/', (req, res) => { // fetch the remote resource and load it into JSDOM. No need for // requestify, but you can use the JSDOM ctor and pass it a string // if you're doing something more complex than hitting an endpoint // (like passing auth, creds, etc.) JSDOM.fromURL('http://localhost:3001/', { runScripts: "dangerously" // allow <script> to run }).then((dom) => { // pass back the result of "x1" from the context of the // loaded dom page. res.send(dom.window.x1); }); }) .listen(3000); 

我然后回来:

 {"p":{"foo":"bar"}}