1

I have this code to render a javascript code with PHP and V8JS but it doesn't work. Does anyone know where the problem is?

<?php

$v8 = new V8Js();
$code = file_get_contents('index2.js');
$result = $v8->executeString( $code );
var_dump($result);
?>

index2.js

const jsdom = require('jsdom');
const { JSDOM } = jsdom;

const dom = new JSDOM(`<!DOCTYPE html><p>Hello world</p>`);
console.log(dom.window.document.querySelector("p").textContent); // "Hello world"

The error that occurs:

Fatal error: Uncaught V8JsScriptException: V8Js::compileString():1: No module loader in index.php on line 6

I imagine the problem is in the require of the node module jsdom

Bruno Andrade
  • 565
  • 1
  • 3
  • 17

1 Answers1

4

In order to require a module, you must register a module loader with setModuleLoader() (see the V8Js API and this post).

You can do something like this:

$v8 = new V8Js();
$v8->setModuleLoader(function($path) {
    return file_get_contents($path);
});

Of course you will need to adjust the code to load the file from the correct directory.

Olivier
  • 13,283
  • 1
  • 8
  • 24