I have lots of *.js files in subfolders and subsubfolders of my Node.js project which I have written recklessly, and now I'm looking for a tool that can iterate over all the files and beautify them.

I found js-beautify package but I'm not sure if it does what I want. Moreover, I doubt a node package is what I want. I think I need a software that I can call from the Ubuntu terminal.

| improve this question | | | | |

Vim supports formatting source code files with the commannd gg=G. gg is a (probably redundant) motion that jumps to the beginning of the file; = is the indent command, and the G motion means "execute until end of file". I know, it sounds like alien talk...

In order to execute this on many files, you can create a file and name it whatever you want, e.g. vim-indent.txt, inside which type the following:


with a trailing line-break.

Basically, this file contains a recording of keys we want to press upon running VIM. The :wq<ENTER> command means "write and quit", and it has to be terminated with a line-break. Without that, vim will just type the command and sit there waiting you to press enter manually.

You can then execute the script on a file like this:

vim -s vim-indent.txt your_file.js

The result is that VIM would open the file your_file.js and "press" all keys recorded in vim-indent.txt, the result of which is applying indentation, writing the file and quitting.

You can automate executing this command on an entire file tree using find:

find [path/to/your/directory] -type f -name '*.js' -exec vim -s vim-indent.txt "{}" \;

Note that it's highly recommended that you copy the entire directory, operate on the copy and check whether you like the result.

| improve this answer | | | | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.