How can I beautify JavaScript code using Command Line?

grom picture grom · Aug 21, 2008 · Viewed 76.3k times · Source

I am writing a batch script in order to beautify JavaScript code. It needs to work on both Windows and Linux.

How can I beautify JavaScript code using the command line tools?

Answer

Alan Storm picture Alan Storm · Aug 26, 2008

First, pick your favorite Javascript based Pretty Print/Beautifier. I prefer the one at http://jsbeautifier.org/, because it's what I found first. Downloads its file https://github.com/beautify-web/js-beautify/blob/master/js/lib/beautify.js

Second, download and install The Mozilla group's Java based Javascript engine, Rhino. "Install" is a little bit misleading; Download the zip file, extract everything, place js.jar in your Java classpath (or Library/Java/Extensions on OS X). You can then run scripts with an invocation similar to this

java -cp js.jar org.mozilla.javascript.tools.shell.Main name-of-script.js

Use the Pretty Print/Beautifier from step 1 to write a small shell script that will read in your javascript file and run it through the Pretty Print/Beautifier from step one. For example

//original code    
(function() { ... js_beautify code ... }());

//new code
print(global.js_beautify(readFile(arguments[0])));

Rhino gives javascript a few extra useful functions that don't necessarily make sense in a browser context, but do in a console context. The function print does what you'd expect, and prints out a string. The function readFile accepts a file path string as an argument and returns the contents of that file.

You'd invoke the above something like

java -cp js.jar org.mozilla.javascript.tools.shell.Main beautify.js file-to-pp.js

You can mix and match Java and Javascript in your Rhino run scripts, so if you know a little Java it shouldn't be too hard to get this running with text-streams as well.