I'm currently switching from restified to Express, and I noticed that the output of res.send({}) in Express has pretty-printed JSON with white space, while the Restify output is minified without white space.
Since the JSON is not for human consumption, I prefer the minified output. Is there an easy way to get Express to output minified JSON without individually changing all the res.send() calls? I would also prefer a setting over adding more middle-ware for performance reasons.
If you just want to pretty print an object and not export it as valid JSON you can use console. dir() . It uses syntax-highlighting, smart indentation, removes quotes from keys and just makes the output as pretty as it gets. Under the hood it is a shortcut for console.
json() is a built-in middleware function in Express. This method is used to parse the incoming requests with JSON payloads and is based upon the bodyparser. This method returns the middleware that only parses JSON and only looks at the requests where the content-type header matches the type option.
To minify json string, first we will convert it to an Object by using JSON. parse() method, then we will use JSON. stringify() method to minify it by passing space ( o ) as an argument.
You can set the json spaces
setting to 0:
var app = express();
app.set('json spaces', 0);
Express will do that automatically when you run it in production mode, though:
NODE_ENV=production node app
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With