javascript-code-runner

Run your JavaScript code snippets in the browser. A sandboxed JavaScript interpreter.

Usage no npm install needed!

<script type="module">
  import javascriptCodeRunner from 'https://cdn.skypack.dev/javascript-code-runner';
</script>

README

JavaScript Code Runner

NPM version NPM downloads

JavaScript Code Runner allows the execution of JavaScript code. This package base on an awesome JS-Interpreter written by Google's Neil Fraser.

Execution is completely isolated from the global JavaScript environment. None of the DOM APIs are exposed. That is the point of a sandbox.

Installation

npm i javascript-code-runner

Usage

import JSrunner from "javascript-code-runner";

const fibonacciCode = `
const result = [];
const fibonacci = (n, result) => {
  var a = 1, b = 1, sum;
  for (var i = 0; i < n; i++) {
    result.push(a);
    sum = a + b;
    a = b;
    b = sum;
  }
}
fibonacci(12, result);
result.join(', ');`;

const { result, message } = JSrunner(fibonacciCode);
console.log(result); // 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144
console.log(message); // null (error message)

Example with a web worker

worker.js

import JSrunner from "javascript-code-runner";

addEventListener("message", (e) => {
  postMessage(JSrunner(e.data));
});