How do I JS-Beautify recursively?

I've run into a similar problem and found a simple cross-platform solution using glob-run:

npm i -g glob-run js-beautify
glob-run html-beautify -r **/*.html

It would be nice if js-beautify supported globs itself, though.


find+xargs is the way to go. It is faster than find with -exec.

find . -name '*.html' | xargs js-beautify 

If for some reason, you have spaces in your filenames, you'll want to do it like this...

find . -name '*.html' -print0 | xargs -0 js-beautify

Finally, if for some strange reason, js-beautify won't work with multiple arguments, then you'll need to tell xargs to only pass in one argument at a time. This isn't much different than using the -exec option, but it's better IMO because it's just more consistent.

find . -name '*.html' | xargs -n 1 js-beautify

Note, you can combine the -print0 and xargs -0 options with xargs -n 1.

edit: As pointed out by T.J. Crowder, the shell will not glob wildcards in double-quotes. This was news to me, perhaps there is some ancient environment out there where that isn't true, and hopefully, you'll never be forced to work in it.


However, JS-beautify does work ... in case of all the files in a directory but not in sub-directory

You've mentioned that JS-beautify works if all the input files are in the same directory. Your command doesn't probably work because you pass all the results from find which might include input files from different directories.

As mentioned in the comment earlier, you could use -exec instead:

find . -type f -name "*.html" -exec js-beautify -r {} \;

Newer versions of GNU find might use this syntax:

find . -type f -name "*.html" -exec js-beautify -r {} +

1) Add these dependencies to your project

npm install --save-dev glob js-beautify

2) Create scripts/format.js

const jsBeautify = require('js-beautify')['js_beautify'];
const fs = require('fs');
const glob = require('glob');

const options = {
  indent_size: 2,
  indent_char: ' ',
  indent_with_tabs: false,
  eol: '\n',
  end_with_newline: true,
  indent_level: 0,
  preserve_newlines: true,
  max_preserve_newlines: 10,
  space_in_paren: false,
  space_in_empty_paren: false,
  jslint_happy: false,
  space_after_anon_function: false,
  brace_style: 'collapse',
  break_chained_methods: false,
  keep_array_indentation: false,
  unescape_strings: false,
  wrap_line_length: 0,
  e4x: false,
  comma_first: false,
  operator_position: 'before-newline'
};

glob('**/!(node_modules)/**/*.js', { absolute: true }, (er, files) => {
  files.forEach(file => {
    console.log(`js-beautify ${file}`);
    const data = fs.readFileSync(file, 'utf8');
    const nextData = jsBeautify(data, options);
    fs.writeFileSync(file, nextData, 'utf8');
  });
});

3) Add a format script to package.json

"scripts": {
  "format": "node ./scripts/format.js"
}

4) In your project, run

npm run format