从NodeJS访问外部.HTML的DOM?

时间:2013-07-24 18:17:48

标签: javascript node.js dom io document.write

一般来说,NodeJS和JavaScript都是新手;我该如何进行基本文件I / O?

read_and_edit_me.html

<!doctype html>
<html lang="en">
    <head></head>
    <body>
        <a href="//foo">bar</a>
    </body>
</html>

rw_dom.js

// Here is how I would do it if this was in <head></head>
document.open();
document.write('<a href="/bar">Out with the old -');
document.write('<a href="/new_bar">in</a> with the new!</a>');

var all_href = [], l = document.links;
document.close();

for (var i = 0; i < l.length; i++) {
    all_href.push(l[i].href);
}

// `all_href` should contain: ["http://{host}/bar", "http://{host}/new_bar"]

2 个答案:

答案 0 :(得分:1)

所以你想在将DOM服务器发送到客户端之前对其进行操作吗? 如果是这样,请看一下(使用“jsdom”): http://marksoper.me/Server-side-DOM-manipulation-in-Nodejs-with-JSDOM-JQuery-and-Mustache-Templates-April-25-2011.html

答案 1 :(得分:0)

@MattiasHognas并不接受我的编辑,所以关闭他的链接这就是我的想法:

require.paths.unshift('/usr/local/lib/node_modules');
var fs    = require('fs'),
    jsdom = require('jsdom');

var read_and_edit_me = fs.readFileSync('read_and_edit_me.html','utf-8');
var document         = jsdom.jsdom(read_and_edit_me);

那么document应该可以像我的问题片段一样使用吗?