【问题标题】:node-restify: how to indent JSON output?node-restify:如何缩进 JSON 输出?
【发布时间】:2012-06-15 06:32:53
【问题描述】:

让 node-restify 输出 JSON 更好的正确方法是什么(即使用换行符和缩进)?

我基本上希望它输出像 JSON.stringify(object, null, 2) 这样的东西,但我看不出有办法配置 restify 来做到这一点。

在不修补restify的情况下实现它的最佳方法是什么?

【问题讨论】:

    标签: javascript json node.js restify


    【解决方案1】:

    您应该可以使用formatters 来实现这一点(请参阅Content Negotiation),只需为application/json 指定自定义一个:

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

    您可以只使用稍加修改的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;
    }
    

    【讨论】:

    • 太好了,这行得通!但是,需要注意的是,您需要通过调用 response.contentType = 'application/json' 将内容类型显式设置为 JSON。否则,restify 会将数据作为八位字节流发送出去。
    • 太棒了,考虑为此提出拉取请求!
    【解决方案2】:

    我相信这是一个更好的解决方案,代码简单,没有任何错误检查程序运行并且似乎没有任何问题:

    https://github.com/restify/node-restify/issues/1042#issuecomment-201542689

    var server = restify.createServer({
        formatters: {
            'application/json': function(req, res, body, cb) {
                return cb(null, JSON.stringify(body, null, '\t'));
            }
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2016-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-25
      • 1970-01-01
      • 2013-05-08
      • 1970-01-01
      相关资源
      最近更新 更多