使 node-restify 输出 JSON 更漂亮(即使用换行符和缩进)的正确方法是什么?
我基本上希望它输出像 JSON.stringify(object, null, 2)
这样的东西,但我看不出有什么办法可以配置 restify 来做到这一点。
在不修补 restify 的情况下实现它的最佳方法是什么?
最佳答案
您应该能够使用 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;
}
关于javascript - Node 重新验证 : how to indent JSON output?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10995601/