Binding Node.js
Binding Node.js code is just as easy as binding JavaScript. Let's see an example: suppose we have written a function called calcMD5
in a Node.js file called test.nodejs
. The function accepts a string and returns its MD5 hash value. The test.nodejs
file contains the following code:
/** test.nodejs */ var crypto = require('crypto'); /** * Calculates the MD5 hash value of a string. * @register {string -> string} */ var calcMD5 = function(str){ return crypto.createHash('md5').update(str).digest('hex'); }
As we can see from the preceding code, we bind Node.js in the same manner that we previously used to bind the client-side JavaScript code. We also invoke it in the same way:
/** 603.opa */ md5 = %%test.calcMD5%%("Hello Opa!"); println("MD5 value: {md5}");
And finally, we compile and run the application:
opa test.nodejs 603.opa --
The result is as shown in the following screenshot: