Respond to JSON or XML requests from a Node.js API

Distributed Systems with Node.js, O'Reilly 2020, has been published!

Here's an NPM Module I came up with which can convert a javascript object to XML, EasyXML. There's a few of them out there already, but they lacked some configurability that I desired, specificially the ability to have pluralized/singular parent/children for array objects (a convention we use at work). The name of the module is easyxml, and can be installed like so:

npm install easyxml

Here is some example code for configuring your converter. This is a universal thing and only needs to be done once.

var easyxml = require('easyxml');
easyxml.configure({
  singularizeChildren: true,
  underscoreAttributes: true,
  rootElement: 'response',
  dateFormat: 'ISO',
  indent: 2,
  manifest: true
});

The main purpose of this module was to be used for an API, which would respond with either JSON or XML depending on what the client asked for. Use this code if you would like to use this module in a similar way.

app.use(function(req, res, next) {
  res.sendData = function(obj) {
    if (req.accepts('json') || req.accepts('text/html')) {
      res.header('Content-Type', 'application/json');
      res.send(obj);
    } else if (req.accepts('application/xml')) {
      res.header('Content-Type', 'text/xml');
      var xml = easyxml.render(obj);
      res.send(xml);
    } else {
      res.send(406);
    }
  };

  next();
});

When you're prepared to send your object to the client, you use res.sendData(obj) instead of res.send(obj).

res.status(200).sendData(obj);

If you find any bugs in the module, report them as issues and I will attempt to fix it. There are certain ambiguous documents which can't be easily converted into XML. When you find these documents, put them into a bug report along with your expected XML output. And as always, you can also submit a pull request with a fix ;).

Tags: #nodejs #npm #xml
Thomas Hunter II Avatar

Thomas has contributed to dozens of enterprise Node.js services and has worked for a company dedicated to securing Node.js. He has spoken at several conferences on Node.js and JavaScript, is an O'Reilly published author, and is an organizer of NodeSchool SF.