What is the proper way to make node-restify output JSON more nicely (i.e. with line-breaks and indentation)?
I basically want it to output something like JSON.stringify(object, null, 2)
would do, but I see no way to configure restify to do that.
What is the best way to achieve it without patching restify?
What is the proper way to make node-restify output JSON more nicely (i.e. with line-breaks and indentation)?
I basically want it to output something like JSON.stringify(object, null, 2)
would do, but I see no way to configure restify to do that.
What is the best way to achieve it without patching restify?
Share Improve this question edited Apr 15, 2013 at 14:19 franzlorenzon 5,9436 gold badges37 silver badges58 bronze badges asked Jun 12, 2012 at 11:19 travelboytravelboy 2,6973 gold badges28 silver badges37 bronze badges2 Answers
Reset to default 8You should be able to achieve this using formatters
(see Content Negotiation), just specify custom one for application/json
:
var server = restify.createServer({
formatters: {
'application/json': myCustomFormatJSON
}
});
You can just use a slightly modified version of 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;
}
I believe this is an even better solutoin, code is simple, without any error checking the program runs and doesn't seem to have any problem:
https://github./restify/node-restify/issues/1042#issuement-201542689
var server = restify.createServer({
formatters: {
'application/json': function(req, res, body, cb) {
return cb(null, JSON.stringify(body, null, '\t'));
}
}
});