Quick-fix for obfuscated Javascript and bad indentation

Technology
Quick-fix for obfuscated Javascript and bad indentation

beautify_20070609.jpg
To save bandwidth and make code harder for third parties to understand, a lot of web developers will use a Javascript compression or obfuscation tool. There are a number of methods used, but almost all of them save space by removing all unnecessary whitespace.

There’s a useful GNU command line utility called “indent” that can help you deconstruct this mess. It won’t fix variables that have been renamed unintelligibly, but, as it’s name implies, it will correct the formatting and indentation of your .js file.

Indent is designed to work with C syntax, but it’s pretty forgiving and does a fairly nice job on C-like syntaxes such as Javascript, Java and (I assume) C#.Net. It can mangle a regexp here or there, but it’s a quick, essential tool if you want to quickly beautify a compressed javascript file and save it to a state that can be read.

De-obfuscate Javascript with indent

indent -bl infile.js outfile.js

You can see some sample output from this command in the image above. That’s a snippet of code from the Google taskbar for Firefox. Note that if you don’t use the second file parameter, indent will just overwrite the original file.

Tweak your block formatting preference
If there’s one thing that programmers all have a strong opinion about, it’s the proper placement of brackets. Specifically, should left brackets be placed on the same line as the function or clause that begins a block, or should they be placed on their own line at the same indentation as the close bracket?

Well, I think they should go on their own line, but if you’re not satisfied with my opinion, you can use indent to get your way:


-br, -bl
Specifying -bl lines up compound statements like this:
if (...)
{
code
}

Specifying -br (the default) makes them look like this:
if (...) {
code
}

This reminds me to mention another caveat, which is that indent uses the wrong block formatting by default. :)

GNU Indent (man page) – Link

What will the next generation of Make: look like? We’re inviting you to shape the future by investing in Make:. By becoming an investor, you help decide what’s next. The future of Make: is in your hands. Learn More.

Tagged
Discuss this article with the rest of the community on our Discord server!

ADVERTISEMENT

Escape to an island of imagination + innovation as Maker Faire Bay Area returns for its 16th iteration!

Prices Increase in....

Days
Hours
Minutes
Seconds
FEEDBACK