2

I need help on running javascript code through NodeJS. So far I have the following code;

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";

I have it as test.js and I run it in the commant prompt as

node test.js

But it gives the following error:

ReferenceError: DOMParser is not defined

What as I doing wrong here. Can any one help please.

2 Answers 2

3

Node.js is running separate from the browser, so you don't get any browser-provided functions. DOMParser is a browser-provided class, and since Node.js runs on a server, there's no browser to provide it. If you want to communicate with your document you'll have to use another method.

Sign up to request clarification or add additional context in comments.

1 Comment

Is there any way that I can pass a XML to a js function from nodeJS?
2

NodeJS does not run inside browser so the DOMParser is not available. However you can use jsdom. Its provided by nodejs. And its available in node package manager.

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";
    }
});

4 Comments

thanks shiplu, But it gives an error.D:\Web\Node\node_modules\jsdom\lib\jsdom.js:177 features = JSON.parse(JSON.stringify(window.document.implementation._fea ^ TypeError: Cannot read property 'implementation' of undefined at exports.env.exports.jsdom.env.processHTML (D:\Web\Node\node_modules\jsdom \lib\jsdom.js:177:59) at Object.exports.env.exports.jsdom.env (D:\Web\Node\node_modules\jsdom\lib\ jsdom.js:268:5)
Did you install jsdom? Usually its done by npm install jsdom
yes I installed it. I installed without any trouble. I run this in windows vista.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.