question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Can't get your solution for #22 work : 'EvalError: Code generation from strings disallowed for this context' (help wanted)

See original GitHub issue

Hi,

I try to reproduce the solution you provide in the issue #22 which look like something I want to be able to do with Javet, ie relying on NodeJS & modules and having an asynchronous solution to get NodeJS and Java working together. By the way, thank you for your effort to make it possible 😉

I came from C++/JAVA and I want to experiment Javascript and NodeJS without leaving the language I managed since 15 years and where I have all my tools…

In fact, I have several issues for now:

  • Javet 2.0.1 crash the JVM with a SIGBUS fatal exception (i’m on Linux Mint), so I use Javet 2.0.0 for now,
  • I can’t get your solution works as @newk5.

My configuration is:

  • NodeJS is accessible from PATH variable (node, npm, …),
  • I ‘install’ node_modules in different locations from global (inside the lib folder of NodeJS) to local (in the folder containing the js script or in another location)

All my attempts results in an ‘JavetExecutionException: EvalError: Code generation from strings disallowed for this context’, or 'JavetExecutionException: Error: Cannot find module ‘unirest’ when something is misconfigured, this is something happening when using a File instead of a String when using setRequireRootDirectory(…), the same issue occured if your String representing the path doesn’t finish with a ‘/’.

I’m not fluent with javascript but it seems that ‘EvalError: Code generation from strings disallowed for this context’ is a javastring issue but the script works as expected when directly run with node.

Your js script from #22 (test-express.js)

/*
npm install express unirest --save [--global] [--prefix /path/to/local/repository]
 */

var unirest = require("unirest");
var req = unirest("POST", "http://mockbin.com/request");

const express = require("express");
const app = express();

console.log("requires 'unirest' and 'express' found");
//makeRequest();
//runServer();
    
function makeRequest(){
    console.log("makeRequest()");
    req.headers({'Accept': 'application/json', 'Content-Type': 'application/json'});
    req.form({ "parameter": 23, "foo": "bar" });
    req.end(function (res) {
        if (res.error) throw new Error(res.error);
        console.log(res.body);
        console.log("http request callback returned, press enter now to start the http server");
    });
}

function runServer(){
    console.log("runServer()");
    app.listen(8991, "0.0.0.0", () => {
        console.log(`Running server`);
    });
}

Your java main with my modification

public class TestExpress2 {
	// These folders contain 'package.json', 'package-lock.json' and 'node_modules' directory
	private static final String local_relative_path  = JavetOSUtils.WORKING_DIRECTORY + "/src/main/javascript/nodejs.demo/";	// OK for cmd: 'node test-express.js' from path <local_relative_path> after 'npm install ... --save'
	private static final String local_absolute_path  = "/s_drive/tmp/nodejs/";													// Attempt to get the script and "node_modules" separated
	private static final String global_absolute_path = "/s_drive/opt/linux.64/nodejs/18.12.0/lib";

	private static final String node_modules_path    = local_absolute_path;
	private static final Path   demo_script          = Paths.get(local_relative_path, "test-express.js");

	public static void main(String[] args) throws JavetException, InterruptedException {
		setCustomLibLoader(false);

        AtomicBoolean isWorking = new AtomicBoolean(true);
        System.out.println("Starting the main thread.");

		try (JavetEnginePool<NodeRuntime> javetEnginePool = new JavetEnginePool<NodeRuntime>()) {
		    javetEnginePool.getConfig().setJSRuntimeType(JSRuntimeType.Node);
		    try (IJavetEngine<NodeRuntime> iJavetEngine = javetEnginePool.getEngine()) {
		        NodeRuntime nodeRuntime = iJavetEngine.getV8Runtime();

/** /			// Not working version as nR.getExecutor(...) reset the RequireRootDirectory
		        nodeRuntime.getNodeModule(NodeModuleModule.class).setRequireRootDirectory(node_modules_path);
	            nodeRuntime.getExecutor(demo_script).executeVoid();
/*/
	            IV8Executor v8exec = nodeRuntime.getExecutor(demo_script);
	        	nodeRuntime.getNodeModule(NodeModuleModule.class).setRequireRootDirectory(node_modules_path);
//	        	nodeRuntime.getNodeModule(NodeModuleModule.class).setRequireRootDirectory(new File(node_modules_path));			// NOK, not the same behavior as with String
	        	v8exec.executeVoid();
/**/

	            // Create a worker thread.
	            Thread thread = new Thread(() -> {
	                System.out.println("Starting the worker thread.");
	                while (isWorking.get()) {
	                    try {
	                        nodeRuntime.await();
	                        Thread.sleep(1);
	                    } catch (InterruptedException e) {
	                        break;
	                    } catch (Exception e) {
	                        e.printStackTrace();
	                    }
	                }
	                System.out.println("Stopping the worker thread.");
	            });
	            // Start the worker thread.
	            thread.start();
	            try (Scanner scanner = new Scanner(System.in)) {
	                nodeRuntime.getGlobalObject().invokeVoid("makeRequest");
	                System.out.println("Press any key to continue. [1]");
	                scanner.nextLine();
	                nodeRuntime.getGlobalObject().invokeVoid("runServer");
	                System.out.println("Press any key to continue. [2]");
	                scanner.nextLine();
	            }
	            System.out.println("Stopping the main thread.");
	            isWorking.set(false);
	            thread.join();
		    }
		}

	}

	private static void setCustomLibLoader(boolean _true) {
		if(!_true)
			return ;

		final String  JavetTemporaryFolder                = "/s_drive/tmp/javet/";
		final boolean letJavetDeployNativeLibrary         = false;
		final boolean dontRaiseErrorOnMultipleClassloader = true;

        JavetLibLoader.setLibLoadingListener(new IJavetLibLoadingListener() {

            @Override
            public File getLibPath(JSRuntimeType jsRuntimeType) {
                return new File(JavetTemporaryFolder);
            }

            @Override
			public boolean isDeploy(JSRuntimeType jsRuntimeType) {
                return letJavetDeployNativeLibrary;
            }

            @Override
            public boolean isSuppressingError(JSRuntimeType jsRuntimeType) {
                return dontRaiseErrorOnMultipleClassloader;
            }

        });
	}

}

Issue Analytics

  • State:open
  • Created 10 months ago
  • Comments:8 (4 by maintainers)

github_iconTop GitHub Comments

2reactions
sanke69commented, Nov 10, 2022

As simple as ’ nodeRuntime.allowEval(true); ’ Thank you very much for your quick answer !

Yes it works 😉

I can now discover the ‘javascript’ world and stay comfortably installed in Java thanks to your work 😉

1reaction
caoccaocommented, Nov 10, 2022

Your script internally calls eval which is disabled by default. Could you enable it and try again?

Read more comments on GitHub >

github_iconTop Results From Across the Web

Error "Code generation from strings disallowed" #1268 - GitHub
EvalError : Code generation from strings disallowed for this context. The solution is to disable devtools this in the config:.
Read more >
"Code generation from strings disallowed for this context" error
hello, I'm having issues running my command $(eval w=$(urlfetch json https://www.helbreath.net/top-eks);r=w.slice(w.search(/Brosky/gi), w.
Read more >
Code generation from strings disallowed for this context
Hey, As the error says code generation is not allowed in Functions/Pages. So using eval or new Function is not allowed.
Read more >
Chrome extension: Uncaught Error: Code generation from ...
This templating library can't be used in a regular extension page because it uses new Function() with a string, which is now disallowed...
Read more >
joel on Twitter: "Y'all seen this before @leeerob? I get an `eval ...
WORKS ON MY MACHINE `Code generation from strings disallowed for this context` ... I get an `eval` error in dev. 9:03 PM ·...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found