如何更好地使node-restify输出JSON,以便更易于阅读(例如换行和缩进)?
我基本上希望它输出类似于JSON.stringify(object, null, 2)
的结果,但我没有找到配置restify实现此功能的方法。
有没有不需要修改restify源码就可以实现此功能的最佳方法?
如何更好地使node-restify输出JSON,以便更易于阅读(例如换行和缩进)?
我基本上希望它输出类似于JSON.stringify(object, null, 2)
的结果,但我没有找到配置restify实现此功能的方法。
有没有不需要修改restify源码就可以实现此功能的最佳方法?
您应该能够通过使用格式化程序
(请参见内容协商)来实现此目标,只需为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;
}
我相信这是一个更好的解决方案,代码简单,没有任何错误检查,程序运行起来似乎没有任何问题:
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'));
}
}
});