node-restify:如何缩进JSON输出?

tra*_*boy 3 javascript json node.js restify

使节点更好地输出JSON的正确方法是什么(即使用换行符和缩进)?

我基本上希望它输出类似的东西JSON.stringify(object, null, 2),但我认为没有办法配置restify来做到这一点.

没有补丁修改的最佳方法是什么?

Jui*_*ter 8

您应该能够使用formatters(请参阅内容协商)来实现此目的,只需为application/json以下内容指定自定义:

var server = restify.createServer({
  formatters: {
    'application/json': myCustomFormatJSON
  }
});
Run Code Online (Sandbox Code Playgroud)

您可以使用原始格式化程序的略微修改版本:

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;
}
Run Code Online (Sandbox Code Playgroud)