node-restify: how to indent JSON output?

javascript, json, node.js, restify

Solution

You should be able to achieve this using `formatters` (see Content Negotiation), just specify custom one for `application/json`:

var server = restify.createServer({
  formatters: {
    'application/json': myCustomFormatJSON
  }
});

You can just use a slightly modified version of original formatter:

function myCustomFormatJSON(req, res, body) {
  if (!body) {
    if (res.getHeader('Content-Length') === undefined &&
        res.contentLength === undefined) {
      res.setHeader('Content-Length', 0);
    }
    return null;
  }

  if (body instanceof Error) {
    // snoop for RestError or HttpError, but don't rely on instanceof
    if ((body.restCode || body.httpCode) && body.body) {
      body = body.body;
    } else {
      body = {
        message: body.message
      };
    }
  }

  if (Buffer.isBuffer(body))
    body = body.toString('base64');

  var data = JSON.stringify(body, null, 2);

  if (res.getHeader('Content-Length') === undefined &&
      res.contentLength === undefined) {
    res.setHeader('Content-Length', Buffer.byteLength(data));
  }

  return data;
}

Problem

What is the proper way to make node-restify output JSON more nicely (i.e. with line-breaks and indentation)? I basically want it to output something like `JSON.stringify(object, null, 2)` would do, but I see no way to configure restify to do that. What is the best way to achieve it without patching restify?

Original source