How can I use JSBeautify from the command line?

Steve Brown picture Steve Brown · Oct 2, 2012 · Viewed 7.6k times · Source

I like jsbeautifier.org and I see they have a github repo with their code.

The readme has two examples of how to use this tool via the command line:

import jsbeautifier
res = jsbeautifier.beautify('your javascript string')
res = jsbeautifier.beautify_file('some_file.js')

and:

opts = jsbeautifier.default_options()
opts.indent_size = 2
res = jsbeautifier.beautify('some javascript', opts)

How can I incorporate this into a script (myjsbeautify.py) so that it can accept either stdin or an argument (file name) and output to stdout ? I also want to use the option to keep array indentation.

Desired syntaxes

cat ugly.js | myjsbeautify.py

or

myjsbeautify.py ugly.js

Answer

cwd picture cwd · Oct 2, 2012

Check out this post on using JSBeautify with Textmate. It has some good instructions on how to install it on your system. On Mac OS X, I used:

cd /tmp
git clone https://github.com/einars/js-beautify.git
cd js-beautify/python
python setup.py install

Then you can simply use js-beautify /path/to/filename.js to have it run.