简体   繁体   English

从NodeJS访问外部.HTML的DOM?

[英]Access DOM of external .HTML from NodeJS?

New to NodeJS and JavaScript in general; 一般而言,NodeJS和JavaScript都是新手; how do I do basic file I/O? 如何执行基本文件I / O?

read_and_edit_me.html read_and_edit_me.html

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

rw_dom.js 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"]

So you want to manipulate DOM serverside before sending it to the client? 因此,您想在将DOM服务器端发送给客户端之前对其进行操作? If so, take a look at this (using "jsdom"): http://marksoper.me/Server-side-DOM-manipulation-in-Nodejs-with-JSDOM-JQuery-and-Mustache-Templates-April-25-2011.html 如果是这样,请看一下(使用“ jsdom”): http ://marksoper.me/Server-side-DOM-manipulation-in-Nodejs-with-JSDOM-JQuery-and-Mustache-Templates-April-25 -2011.html

@MattiasHognas didn't accept my edit, so going off his link this is what I am thinking was meant: @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);

Then document should be able to used as in my question's snippet? 然后document应该可以用作我的问题的摘要吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM