如何使用Rhino shell将JavaScript代码序列化为文件?

时间:2012-06-22 16:11:00

标签: java javascript serialization rhino

我使用Rhino作为Ant构建过程的一部分来捆绑和缩小JavaScript。除此之外,我还想预编译客户端模板,即将它们从标记编译为JavaScript。乍一看,我认为Rhino的serialize()方法可以做到,但情况似乎并非如此。

// 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" );

这会导致写入二进制文件。我想要的是一个包含已编译模板的文本文件。

如果使用serialize()不是答案,那么是什么?由于它是Rhino,因此也可以导入Java类。副手,我无法想办法做到这一点。

我知道这可以在Node中完成,但我现在无法将构建过程从Ant-Rhino迁移到Grunt-Node。

2 个答案:

答案 0 :(得分:1)

在我寻找答案时我came across SpiderMonkey,Rhino的C / C ++姐妹,有一个uneval()函数,你可以猜到这与JavaScript的eval()相反。功能。再过一次Google搜索,I found Rhino在1.5R5中实现了uneval()。这可能是唯一文档,提到Rhino具有此功能(or not)。

话虽如此,这是解决方案:

// 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();

答案 1 :(得分:0)

在javascript中编写一个函数,您可以从Java调用该函数,返回您需要的字符串值。