使node-restify輸出JSON更好的方法(即使用換行符和縮進)有什麼正確的方法?node-restify:如何縮進JSON輸出?
我基本上想要它輸出類似JSON.stringify(object, null, 2)
會做,但我看不到配置restify來做到這一點。
如何在不修補restify的情況下實現它的最佳方法是什麼?
使node-restify輸出JSON更好的方法(即使用換行符和縮進)有什麼正確的方法?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;
}
我相信這是一個更好的解決方案,代碼很簡單,沒有任何錯誤檢查程序運行,似乎沒有任何問題:
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'));
}
}
});
大,這個作品!但是,應該注意的是,您需要通過調用response.contentType ='application/json'將內容類型顯式設置爲JSON。否則,restify會將數據作爲八位字節流發送出去。 – travelboy
太棒了,可以考慮爲此提出一個拉取請求! – bcoughlan