gitmyhub

otto

Go ★ 8.4k updated 1y ago

A JavaScript interpreter in Go (golang)

A JavaScript interpreter built in Go that lets Go applications run JavaScript code at runtime, making it easy to add user-scriptable logic to any Go program.

GoJavaScriptsetup: moderatecomplexity 3/5

Otto is a JavaScript interpreter written in Go, a compiled programming language made by Google. It lets Go programs run JavaScript code directly, without needing a separate JavaScript runtime like Node.js. Developers use it to add scripting capabilities to Go applications, such as letting users write small scripts that the application can evaluate at runtime.

The library works by creating a virtual machine object in Go. You pass JavaScript code as a string to that machine, and it runs it. You can also pass values from Go into the JavaScript environment (numbers, strings, functions) and read results back out. This two-way bridge is the main reason people use it: you can write core application logic in Go and expose pieces of it to JavaScript scripts that users or operators might want to customize.

There is also a standalone command-line tool included in the repository that lets you run JavaScript files directly from your terminal, without writing any Go code. For developers who want to work with JavaScript's syntax structure rather than executing it, there is a separate parser package that reads JavaScript and produces an abstract syntax tree, which is a data structure that represents the code's structure.

Otto targets ECMAScript 5, which is the version of the JavaScript standard from 2009. It does not support most ES6 features introduced in 2015 and later. There are also some known limitations with regular expressions, since Go uses a regex engine that does not support certain patterns that JavaScript code sometimes relies on. Functions like setTimeout and setInterval, which are common in browser JavaScript, are not included because they are not part of the core language standard and require an event loop to work correctly.

The README includes a code example for stopping scripts that run too long, which is useful when running untrusted JavaScript. Optional integration with the Underscore.js utility library is also supported.

Where it fits