Serving Up Formatted Data
Problem
Instead of serving up a web page or sending plain text, you want to return formatted
data, such as XML, to the browser.
Solution
Use Node module(s) to help format the data. For example, if you want to return XML,
you can use a module to create the formatted data:
var XMLWriter = require('xml-writer'); var xw = new XMLWriter; // start doc and root element xw.startDocument().startElement("resources"); // resource xw.startElement("resource"); xw.writeElement("title","Ecma-262 Edition 6"); xw.writeElement("url","http://wiki.ecmascript.org/doku.php?id=harmony:specific ation_drafts"); // end resource xw.endElement(); // end resources xw.endElement();
Then create the appropriate header to go with the data, and return the data to the browser:
// end resources xw.endElement(); res.writeHeader(200, {"Content-Type": "application/xml", "Access-Control-Allow -Origin": "*"}); res.end(xw.toString(),"utf8");
Web servers frequently serve up static or server-side generated resources, but just as frequently, what’s returned to the browser is formatted data that’s then processed in the web page before display.
we examined one use of data formatted as XML that’s gen‐ erated by a Node application on the server and then processed using the DOM API in the browser. Parts of the server application have been excerpted out for the solution. There are two key elements to generating and returning formatted data.
The first is to make use of whatever Node library to simplify the generation of the data, and the second is to make sure that the header data sent with the data is appropriate for the data. In the solution, the xml-writer module is used to assist us in creating proper XML.
This isn’t one of the modules installed with Node by default, so we have to install it using npm, the Node Package Manager:
npm install xml-writer
This installs the xml-writer module in the local project directory, in the /nodemodules subdirectory. To install the module globally, which makes it available for all projects, use:
npm install xml-writer -g
Then it’s just a simple matter of creating a new XML document, a root element, and then each resource element, as demonstrated in the solution. It’s true, we could just build the XML string ourselves, but that’s a pain.
And it’s too easy to make mistakes that are then hard to discover. One of the best things about Node is the enormous number of modules available to do most anything we can think of. Not only do we not have to write the code ourselves, but most of the modules have been thoroughly tested and actively maintained.
No comments:
Post a Comment