Running Javascript code through NodeJS

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.

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.

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