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

3

如何更好地使node-restify输出JSON,以便更易于阅读(例如换行和缩进)?

我基本上希望它输出类似于JSON.stringify(object, null, 2)的结果,但我没有找到配置restify实现此功能的方法。

有没有不需要修改restify源码就可以实现此功能的最佳方法?

2个回答

8

您应该能够通过使用格式化程序(请参见内容协商)来实现此目标,只需为application/json指定自定义格式化程序即可:

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

您可以使用稍微修改过的原始格式化程序

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;
}

太好了,这个可行!但是需要注意的是,您需要通过调用response.contentType = 'application/json'来显式设置内容类型为JSON。否则,restify将以八位字节流的形式发送数据。 - travelboy
太棒了,考虑为此提交一个拉取请求! - bcoughlan

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接