2012-06-12 22 views
3

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

我基本上想要它输出类似JSON.stringify(object, null, 2)会做,但我看不到配置restify来做到这一点。

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

回答

8

你应该能够做到这一点使用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; 
} 
+0

大,这个作品!但是,应该注意的是,您需要通过调用response.contentType ='application/json'将内容类型显式设置为JSON。否则,restify会将数据作为八位字节流发送出去。 – travelboy

+0

太棒了,可以考虑为此提出一个拉取请求! – bcoughlan