jck jck - 1 year ago 164
Javascript Question

How to beautify/prettify a Json/JS file in a node.js script

I am searching a way to prettify Json files in a node.js script (not CLI). I found a lot of npm beautifier packages, but none that can simply beautify directly a file.

There is esbeautifier that do what I am searching to do, but the exemples only shows CLI commands: https://github.com/royriojas/esbeautifier Is there a way to use it in a Javascript?

Answer Source

you can use the tool esformatter.

edit by @jck: here is JS snippet that works using fs:

var esformatter = require('esformatter');
var fs = require('fs');
var filename = "./myFile.json";
var codeStr = fs.readFileSync(filename).toString();
var formattedCode = esformatter.format(codeStr);
fs.writeFile(filename, formattedCode);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download