关于javascript:如何从节点REPL用jsdom解析DOM

how to parse a DOM with jsdom from a node REPL

我正在尝试编写一些DOM解析代码,以便从节点REPL环境中运行。以下是SSCCE:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
"use strict";

var jsdom = require("jsdom");

var html="";

function parse(html, x) {
    jsdom.env(html, function(errors, window) {
        x.window = window;
    });
}

var x = {};
parse(html, x);
console.log(x.window);

这个想法是,在调用parse函数之后,我将在我的x对象中提供已解析的DOM。

当我将上面的代码放入文件j.js并从REPL加载时,我得到:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
> .load j.js
>"use strict";
'use strict'
> var jsdom = require("jsdom");
undefined
> var html="";
undefined
> function parse(html, x) {
...     jsdom.env(html, function(errors, window) {
.....         x.window = window;
.....     });
... }
undefined
> var x = {};
undefined
> parse(html, x);
undefined
> console.log(x.window);
undefined
undefined
>

为什么代码无法分配x.window属性?


jsdom.env回调被异步评估。这意味着在大多数情况下(可能总是)console.log(x.window)x.window = window;赋值之前执行。

最简单的解决方法是传递分配后执行的回调函数:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
...

function parse(html, x, done) {
    jsdom.env(html, function(errors, window) {
        x.window = window;
        done();
    });
}

var x = {};

parse(html, x, function() {
    console.log(x);
});