node-restify: ¿cómo sangrar la salida JSON?

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?

preguntado el 12 de junio de 12 a las 12:06

2 Respuestas

Debería poder lograr esto usando formatters (consulte la sección del Negociación de contenido), 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;
}

Respondido el 12 de junio de 12 a las 21:06

Great, this works! However, it should be noted that you need to explicitly set the content type to JSON by calling response.contentType = 'application/json'. Otherwise, restify will send the data out as octet stream. - viajero

Awesome, consider putting a pull request in for that! - bcoughlan

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.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'));
        }
    }
});

Respondido 06 Jul 16, 23:07

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.