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

Looking for a better way to manage your org's technical proposals?

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 Hunter II is a Software Engineer with 18+ years building scalable, production-grade systems. Deep expertise in Node.js, observability, and developer tooling, with a strong track record of driving architectural decisions, mentoring engineers, and improving customer facing technical documentation. Author of 5 books (including O'Reilly), certified by the OpenJS Foundation, and frequent international conference speaker.