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); |
这个想法是,在调用
当我将上面的代码放入文件
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 > |
为什么代码无法分配
最简单的解决方法是传递分配后执行的回调函数:
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); }); |