Skip to content

Repository files navigation

NodeJS Eval

Evaluate arbitrary JavaScript from Python, using a NodeJS sidecar process.

This combines:

  • The Python nodejs-bin project, which bundles NodeJS (with npm and npx) into a PyPI package, and
  • The JavaScript/TypeScript http-eval project, which runs a JavaScript evaluation server on a Unix domain socket.

PyPI - VersionPyPI - Python Version


Table of Contents

Installation

pip install nodejs-eval

License

nodejs-eval is distributed under the terms of the MIT license.

Usage instructions

Basic synchronous call

JavaScript code is evaluated as a function body within a synchronous or asynchronous JavaScript function, within an ECMAScript module.

Note that the NodeJS evaluator always only supports async mode on the Python side. However, the supplied JavaScript code can be either sync or async.

fromnodejs_evalimportevaluatorasyncwithevaluator() ase:
result=awaite.run("return 6*7;")
assertresult==42

Basic asynchronous call

fromnodejs_evalimportevaluatorasyncwithevaluator() ase:
result=awaite.run_async(
"""await new Promise(r => setTimeout(r, 2000));return 6*7;""")
assertresult==42

Storing state on this

Evaluations run with a consistent JavaScript this context, so state can be stored on it:

fromnodejs_evalimportevaluatorasyncwithevaluator() ase:
awaite.run("this.x = 6*7;")
result=awaite.run("return this.x;")
assertresult==42

Import using dynamic await import()

Because code is executed within an ECMAScript module, you can use the dynamic async import() to import other modules.

This is easiest done in async mode:

fromnodejs_evalimportevaluatorasyncwithevaluator() ase:
result=awaite.run_async(
"""const os = await import("os");return os.cpus();"""
)
assertlen(result) >0

About

Evaluate arbitrary JavaScript from Python using a NodeJS sidecar

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages