簡體   English   中英

通過NodeJS運行Javascript代碼

[英]Running Javascript code through NodeJS

我需要有關通過NodeJS運行javascript代碼的幫助。 到目前為止,我有以下代碼;

txt="<bookstore><book>";
txt=txt+"<title>Everyday Italian</title>";
txt=txt+"<author>Giada De Laurentiis</author>";
txt=txt+"<year>2005</year>";
txt=txt+"</book></bookstore>";

parser=new DOMParser();
xmlDoc=parser.parseFromString(txt,"text/xml");
x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];
x.nodeValue="Diffrent Title";

我將其作為test.js,並在命令提示符下將其運行為

node test.js

但是它給出了以下錯誤:

ReferenceError: DOMParser is not defined

我在這里做錯了什么。 有人可以幫忙嗎?

Node.js與瀏覽器是分開運行的,因此您沒有任何瀏覽器提供的功能。 DOMParser是瀏覽器提供的類,並且由於Node.js在服務器上運行,因此沒有瀏覽器可以提供它。 如果要與文檔進行通信,則必須使用另一種方法。

NodeJS不在瀏覽器中運行,因此DOMParser不可用。 但是,您可以使用jsdom 它由nodejs提供。 及其在節點包管理器中可用

var jsdom = require("jsdom");
jsdom.env({
    html: txt,
    scripts: ["http://code.jquery.com/jquery.js"],
    done: function(errors, window) {
        x = window.getElementsByTagName("title")[0].childNodes[0];
        x.nodeValue="Diffrent Title";
    }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM