Search code examples
javajavascriptserializationrhino

How can I serialize JavaScript code to a file using Rhino shell?


I am using Rhino as part of an Ant build process to bundle and minify JavaScript. In addition to that, I would also like pre-compile client-side templates, i.e. compile them from markup to JavaScript. At a glance, I thought Rhino's serialize() method would do it but that does not seem to be the case.

// Load templating engine
load( "engine.js" );

// Read template file
var template = readFile( "foo.template" ),

// Compile template
compiled = engine.compile( template );

// Write compiled template to file
serialize( compiled, "compiledFoo.js" );

This results in a binary file being written. What I want is a text file which contains the compiled template.

If using serialize() is not the answer, then what is? Since it's Rhino, it would be possible to import Java classes as well. Offhand, I can't figure out a way to do it.

I know this can be done in Node but I'm not in a position to migrate the build process from Ant-Rhino to Grunt-Node right now.


Solution

  • In my search for an answer I came across the fact that SpiderMonkey, Rhino's C/C++ sister, has an uneval() function, which as you can guess does the opposite of JavaScript's eval() function. One more Google search later, I found that Rhino implemented uneval() in 1.5R5. This may be the only documentation that mentions Rhino has this feature (or not).

    That being said, here is the solution:

    // Load the templating engine
    load( "engine.js" );
    
    // Read the template file
    var template = readFile( "foo.template" ),
    
    // Compile the template markup to JavaScript
    compiled = engine.compile( template ),
    
    // Un-evaluate the compiled template to text
    code = uneval( compiled ),
    
    // Create the file for the code
    out = new java.io.FileWriter( "foo.js" );
    
    // Write the code to the file
    out.write( code, 0, code.length );
    out.flush();
    out.close();
    
    quit();