Skip to content

Instantly share code, notes, and snippets.

@Dacesilian
Created July 26, 2021 06:55
Show Gist options
  • Save Dacesilian/3354367ea365ffb781f2d0a46629294b to your computer and use it in GitHub Desktop.
Save Dacesilian/3354367ea365ffb781f2d0a46629294b to your computer and use it in GitHub Desktop.
How to call beautify.js from Java using GraalJS
// https://github.com/beautify-web/js-beautify
// https://github.com/oracle/graaljs
// Inspired by https://gist.github.com/fedochet/d41442e735eaa277937a094ab8e5fc8f
import org.apache.commons.io.IOUtils;
import org.graalvm.polyglot.Context;
import org.graalvm.polyglot.HostAccess;
import org.graalvm.polyglot.PolyglotAccess;
import org.graalvm.polyglot.Value;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
public class JavascriptBeautifierForJava {
private static final String BEAUTIFY_JS_RESOURCE = "lib/beautify.js";
private static final String BEAUTIFY_METHOD_NAME = "js_beautify";
private static JavascriptBeautifierForJava instance;
public static JavascriptBeautifierForJava getInstance() {
if (instance == null) {
instance = new JavascriptBeautifierForJava();
}
return instance;
}
private Context context = null;
private Value v = null;
private JavascriptBeautifierForJava() {
context = Context.newBuilder("js")
.allowHostAccess(HostAccess.NONE)
.allowHostClassLookup(cl -> false)
.allowIO(false)
.allowPolyglotAccess(PolyglotAccess.NONE)
.build();
context.eval("js", "var global = this;");
InputStream is = getClass().getClassLoader().getResourceAsStream(BEAUTIFY_JS_RESOURCE);
try {
String module = IOUtils.toString(is, StandardCharsets.UTF_8);
context.eval("js", module);
v = context.eval("js", "(function(a, b) { return " + BEAUTIFY_METHOD_NAME + "(a, b) })");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public String beautify(String javascriptCode) {
return v.execute(javascriptCode, null).asString();
}
public static void main(String[] args) {
String unformattedJs = "var a = 1; b = 2; var user = { name : \n \"Andrew\"}";
JavascriptBeautifierForJava javascriptBeautifierForJava = getInstance();
String formattedJs = javascriptBeautifierForJava.beautify(unformattedJs);
System.out.println(formattedJs);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment