Skip to content

Using erlv8

yrashk edited this page Jan 16, 2011 · 13 revisions
Clone this wiki locally

Using erlv8

Lets start with some basics. First of all, ensure that erlv8 application is started:

application:start(erlv8).

Now, in order to create a JavaScript VM you should call erlv8_vm:start():

{ok, VM} = erlv8_vm:start().

it will return something like

{ok,<0.38.0>}

As you can see, it creates a worker process that is crucial for our future interaction with the VM. Now, the simplest way to try the taste of JavaScript inside your Erlang app is to run a script:

erlv8_vm:run(VM,"f = function (x) { return x * 10 }; f(10)").

Since it is a valid JavaScript, it will rightfully return

{ok,100}

Pretty easy so far, eh? Lets make a little bit more interesting. What if you want to plant a globally available object so that your script can use it? Nothing easier! First, get the global object:

Global = erlv8_vm:global(VM).

and then just set its slot value:

Global:set_value("my_object","It is actually a string").

Lets test it:

erlv8_vm:run(VM,"my_object").

And that's the result we were expecting:

{ok,"It is actually a string"}

You can retrieve the same value by using get_value:

Global:get_value("my_object"). % returns:
"It is actually a string"

If you need a whole object as a proplist, that has never been easier:

Global:proplist(). % returns:
[{"my_object","It is actually a string"}]

If you want to use something more complicated than a primitive object (such as string, number, boolean, etc.), please read more about it at Data Types, here we'll give just one example:

Global:set_value("obj",erlv8_object:new([{"property","value"}])), %% you can use ?V8Obj() macro instead of erlv8_new
{ok, Obj} = erlv8_vm:run(VM,"obj"),
Obj:proplist(). %% results in:
[{"property","value"}]

By the way, what if we had an error in our code?

{Resolution, Value} = erlv8_vm:run(VM,"f = function (x) { return x * 10 }; f(10"). % returns:
{compilation_failed,{erlv8_object,<<>>}}

You can inspect that Value with proplist():

Value:proplist(). % results in
[{"message","Unexpected end of input"},
 {"stack","SyntaxError: Unexpected end of input"},
 {"type","unexpected_eos"},
 {"arguments",[]},
 {"name","SyntaxError"}]

Now that's understandable!

You can also expose Erlang-implemented functionality in JavaScript, that's pretty interesting, too.

P.S. When you're done, shut the VM down:

erlv8_vm:stop(VM).

Alternatively, stopping erlv8 application will do that for you as well.

Something went wrong with that request. Please try again.