2012-06-12 67 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