Source

v8erl / erl / v8.erl

-module(v8).
-export([load/0,
         context/0,
         script/2]).
-export([test/0]).
-define(LIB, "v8erl").
-define(DRV_RUN_SCRIPT, $R).

load() ->
    case whereis(v8erl) of
        undefined ->
            case erl_ddll:load_driver("lib", ?LIB) of
                ok ->
                    ok;
                {error, already_loaded} ->
                    ok;
                {error, Err} ->
                    {error, erl_ddll:format_error(Err)}
            end;
        _ ->
            ok
    end.

context() ->
    open_port({spawn, ?LIB}, [binary]).

destroy(Context) when is_port(Context) ->
    port_close(Context).

script(Context, Script) when is_port(Context) ->
    true = erlang:port_connect(Context, self()),
    true = erlang:port_command(Context, Script),
    receive
	Result ->
	    Result
    after
	3000 ->
	    {error, timeout}
    end.

test() ->
    io:format("load v8: ~w~n", [load()]),
    Context = context(),
    case script(Context, <<"var f = function() { return true; }; g();">>) of
	{ok, Result} ->
	    io:format("script value: ~w~n", [Result]);
	{error, Error} ->
	    io:format("script error: ~s~n", [Error])
    end,
    destroy(Context),
    ok.