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

2020-04-10 00:55发布

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?

3条回答
小情绪 Triste *
2楼-- · 2020-04-10 01:37

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);
查看更多
叛逆
3楼-- · 2020-04-10 01:37

Alternatively, check out prettyjson! It has been great for me!

查看更多
一夜七次
4楼-- · 2020-04-10 01:44

You can prettyprint JSON easily by providing parameters to JSON.stringify().

Many people use this kind of call to prettyprint JSON output. It's still valid JSON, it just contains indentation and newlines.

 JSON.stringify(myObject, null, 2);
查看更多
登录 后发表回答