### EventLoop Lifecycle Management Source: https://context7.com/dop251/goja_nodejs/llms.txt Demonstrates starting, stopping, and terminating the event loop. Use StartInForeground to recover from panics. ```go loop := eventloop.NewEventLoop() // Start the loop in a background goroutine loop.Start() // ... schedule work with RunOnLoop / SetTimeout ... // Pause the loop; active timers remain (can Start() again) remaining := loop.Stop() println("pending jobs:", remaining) // Or terminate completely, cancelling all active timers loop.Start() loop.Terminate() // blocks until all goroutines are gone // StartInForeground — useful when you want to recover panics go func() { defer func() { if r := recover(); r != nil { log.Println("recovered:", r) } }() loop2 := eventloop.NewEventLoop() loop2.StartInForeground() // blocks until Stop/Terminate }() ``` -------------------------------- ### Install @dop251/types-goja_nodejs-url Source: https://github.com/dop251/goja_nodejs/blob/master/url/types/README.md Install the type definitions for the goja_nodejs url module as a development dependency. ```shell npm install --save-dev @dop251/types-goja_nodejs-url ``` -------------------------------- ### EventLoop Lifecycle Management Source: https://context7.com/dop251/goja_nodejs/llms.txt Manages the lifecycle of the event loop, including starting, stopping, and terminating. ```APIDOC ## EventLoop.Start / StartInForeground / Stop / StopNoWait / Terminate Lifecycle management for long-running loops. ```go loop := eventloop.NewEventLoop() // Start the loop in a background goroutine loop.Start() // ... schedule work with RunOnLoop / SetTimeout ... // Pause the loop; active timers remain (can Start() again) remaining := loop.Stop() println("pending jobs:", remaining) // Or terminate completely, cancelling all active timers loop.Start() loop.Terminate() // blocks until all goroutines are gone // StartInForeground — useful when you want to recover panics go func() { defer func() { if r := recover(); r != nil { log.Println("recovered:", r) } }() loop2 := eventloop.NewEventLoop() loop2.StartInForeground() // blocks until Stop/Terminate }() ``` ``` -------------------------------- ### Create and Enable a New Registry with Custom Loaders Source: https://context7.com/dop251/goja_nodejs/llms.txt Demonstrates creating a default registry and a custom registry with an in-memory source loader and global folders. The custom registry is then enabled for a Goja runtime. ```go package main import ( "github.com/dop251/goja" "github.com/dop251/goja_nodejs/require" ) func main() { // Default registry — loads modules from the host filesystem registry := require.NewRegistry() // Registry with a custom in-memory source loader sources := map[string]string{ "/app/math.js": `exports.add = (a, b) => a + b;`, } customRegistry := require.NewRegistry( require.WithLoader(func(path string) ([]byte, error) { if src, ok := sources[path]; ok { return []byte(src), nil } return nil, require.ModuleFileDoesNotExistError }), require.WithGlobalFolders("/opt/node_modules"), ) rt := goja.New() customRegistry.Enable(rt) v, _ := rt.RunString(` var math = require("/app/math.js"); math.add(3, 4); // => 7 `) _ = registry println(v.ToInteger()) // 7 } ``` -------------------------------- ### Util.Format for printf-style formatting Source: https://context7.com/dop251/goja_nodejs/llms.txt `util.New` creates a Go-side `Util` instance; `Format` renders a printf-style format string. Supports %s, %d, %j, and %%. ```go import ( "bytes" "fmt" "github.com/dop251/goja" "github.com/dop251/goja_nodejs/require" "github.com/dop251/goja_nodejs/util" ) registry := require.NewRegistry() rt := goja.New() registry.Enable(rt) u := util.New(rt) var buf bytes.Buffer u.Format(&buf, "hello %s, count=%d, data=%j, literal=%%", rt.ToValue("world"), rt.ToValue(42), rt.ToValue(map[string]interface{}{"ok": true}), ) fmt.Println(buf.String()) // hello world, count=42, data={"ok":true}, literal=% // Or use it from JavaScript via require rt.RunString( ` var util = require("util"); console.log(util.format("name=%s age=%d info=%j", "Alice", 30, {admin:true})); // name=Alice age=30 info={"admin":true} `) ``` -------------------------------- ### URL Constructor (JS API) Source: https://context7.com/dop251/goja_nodejs/llms.txt Supports absolute URL construction and base-relative resolution with IDNA hostname normalization. Ensure require.Registry and url.Enable are called. ```go registry := require.NewRegistry() rt := goja.New() registry.Enable(rt) url.Enable(rt) rt.RunString( "\n // Relative URL resolved against a base\n var base = new URL(\"https://example.com/a/b/\");\n var rel = new URL(\"../c\", base);\n console.log(rel.href); // https://example.com/a/c\n\n // IDNA hostname normalisation\n var idn = new URL(\"https://\u4e2d\u6587.com/path\");\n console.log(idn.hostname); // xn--fiq228c.com (Punycode)\n\n // Credentials in URL\n var auth = new URL(\"https://user:pass@secure.example.com/\");\n console.log(auth.username); // user\n console.log(auth.password); // pass\n\n // toString / toJSON\n console.log(rel.toString()); // https://example.com/a/c\n console.log(JSON.stringify(rel)); // \"https://example.com/a/c\"\n\n // Invalid URL throws\n try {\n new URL(\"not a url\");\n } catch(e) {\n console.log(e.code); // ERR_INVALID_URL\n } ") ``` -------------------------------- ### Create a New Registry with a Custom Source Loader Source: https://context7.com/dop251/goja_nodejs/llms.txt A shorthand constructor for creating a registry with a specified source loader function. This is useful for integrating with custom virtual file systems. ```go registry := require.NewRegistryWithLoader(func(path string) ([]byte, error) { data, err := myVirtualFS.ReadFile(path) if err != nil { return nil, require.ModuleFileDoesNotExistError } return data, nil }) rt := goja.New() registry.Enable(rt) rt.RunString(`var m = require("mymod"); m.hello();`) ``` -------------------------------- ### Buffer.from / Buffer.alloc / Buffer.concat (JS API) Source: https://context7.com/dop251/goja_nodejs/llms.txt Demonstrates the static factory methods available on the `Buffer` constructor in JavaScript, including creating Buffers from strings or hex, allocating Buffers with specific sizes and fill patterns, and concatenating Buffers. ```APIDOC ## Buffer.from / Buffer.alloc / Buffer.concat (JS API) ### Description Static factory methods available on the `Buffer` constructor in JavaScript. ### Usage ```javascript // Buffer.from — string with encoding var b1 = Buffer.from("hello world", "utf8"); console.log(b1.length); // 11 // Buffer.from — hex string var b2 = Buffer.from("deadbeef", "hex"); console.log(b2.toString("hex")); // deadbeef // Buffer.alloc — zeroed buffer var b3 = Buffer.alloc(4); console.log(b3.toString("hex")); // 00000000 // Buffer.alloc — filled buffer var b4 = Buffer.alloc(4, 0xff); console.log(b4.toString("hex")); // ffffffff // Buffer.alloc — filled with string pattern var b5 = Buffer.alloc(6, "ab", "utf8"); console.log(b5.toString()); // ababab // Buffer.concat var merged = Buffer.concat([b1, b2]); console.log(merged.length); // 15 // Buffer.concat with explicit totalLength (truncates/zero-pads) var truncated = Buffer.concat([b1, b2], 5); console.log(truncated.toString()); // hello ``` ``` -------------------------------- ### Enable console module with StdPrinter Source: https://context7.com/dop251/goja_nodejs/llms.txt Registers the console module and injects a console global using the default StdPrinter (stdout/stderr). ```go import ( "github.com/dop251/goja" "github.com/dop251/goja_nodejs/console" "github.com/dop251/goja_nodejs/require" ) registry := require.NewRegistry() rt := goja.New() registry.Enable(rt) console.Enable(rt) rt.RunString(` console.log("hello %s", "world"); // stdout: hello world console.info("count: %d", 42); // stdout: count: 42 console.warn("watch out: %j", {x: 1}); // stderr: watch out: {"x":1} console.error("oops"); // stderr: oops console.debug("debug msg"); // stdout: debug msg `) ``` -------------------------------- ### console.Enable Source: https://context7.com/dop251/goja_nodejs/llms.txt Registers the `console` module and injects a `console` global into a runtime, using the default `StdPrinter`. ```APIDOC ## console — Console Module ### console.Enable Registers the `console` module and injects a `console` global into a runtime, using the default `StdPrinter` (stdout/stderr via the standard `log` package). ```go import ( "github.com/dop251/goja" "github.com/dop251/goja_nodejs/console" "github.com/dop251/goja_nodejs/require" ) registry := require.NewRegistry() rt := goja.New() registry.Enable(rt) console.Enable(rt) rt.RunString(` console.log("hello %s", "world"); // stdout: hello world console.info("count: %d", 42); // stdout: count: 42 console.warn("watch out: %j", {x: 1}); // stderr: watch out: {"x":1} console.error("oops"); // stderr: oops console.debug("debug msg"); // stdout: debug msg `) ``` ``` -------------------------------- ### Enable Node.js require in Goja Source: https://github.com/dop251/goja_nodejs/blob/master/README.md Demonstrates how to set up a Goja runtime with the require module enabled to load JavaScript files as Node.js modules. Ensure the registry is created before enabling it on the runtime. ```go package main import ( "github.com/dop251/goja" "github.com/dop251/goja_nodejs/require" ) func main() { registry := new(require.Registry) // this can be shared by multiple runtimes runtime := goja.New() req := registry.Enable(runtime) runtime.RunString( ` var m = require("./m.js"); m.test(); ` ) m, err := req.Require("./m.js") _, _ = m, err } ``` -------------------------------- ### Enable Buffer module Source: https://context7.com/dop251/goja_nodejs/llms.txt Injects the Buffer global into a runtime, allowing Node.js Buffer operations. ```go import ( "github.com/dop251/goja" "github.com/dop251/goja_nodejs/buffer" "github.com/dop251/goja_nodejs/require" ) registry := require.NewRegistry() rt := goja.New() registry.Enable(rt) buffer.Enable(rt) // Buffer is now a global rt.RunString(` var b = Buffer.from("hello", "utf8"); console.log(b.toString("hex")); // 68656c6c6f console.log(b.toString("base64")); // aGVsbG8= console.log(b.length); // 5 `) ``` -------------------------------- ### Register a Native Module with Registry Source: https://context7.com/dop251/goja_nodejs/llms.txt Registers a Go-implemented module with a specific `Registry` instance. This Go module will take precedence over file-system modules with the same name when required. ```go registry := require.NewRegistry() // Register a Go module that exposes a "greet" function registry.RegisterNativeModule("myapp/greeter", func(rt *goja.Runtime, module *goja.Object) { exports := module.Get("exports").(*goja.Object) exports.Set("greet", func(name string) string { return "Hello, " + name + "!" }) }) rt := goja.New() registry.Enable(rt) v, _ := rt.RunString(` var g = require("myapp/greeter"); g.greet("World"); // => "Hello, World!" `) println(v.String()) // Hello, World! ``` -------------------------------- ### JavaScript Buffer Factory Methods Source: https://context7.com/dop251/goja_nodejs/llms.txt Demonstrates static factory methods on the JavaScript `Buffer` constructor, including `Buffer.from` for creating buffers from strings or hex/base64 data, `Buffer.alloc` for allocating zeroed or filled buffers, and `Buffer.concat` for merging buffers. ```javascript loop := eventloop.NewEventLoop() loop.Run(func(vm *goja.Runtime) { vm.RunString(` // Buffer.from — string with encoding var b1 = Buffer.from("hello world", "utf8"); console.log(b1.length); // 11 // Buffer.from — hex string var b2 = Buffer.from("deadbeef", "hex"); console.log(b2.toString("hex")); // deadbeef // Buffer.alloc — zeroed buffer var b3 = Buffer.alloc(4); console.log(b3.toString("hex")); // 00000000 // Buffer.alloc — filled buffer var b4 = Buffer.alloc(4, 0xff); console.log(b4.toString("hex")); // ffffffff // Buffer.alloc — filled with string pattern var b5 = Buffer.alloc(6, "ab", "utf8"); console.log(b5.toString()); // ababab // Buffer.concat var merged = Buffer.concat([b1, b2]); console.log(merged.length); // 15 // Buffer.concat with explicit totalLength (truncates/zero-pads) var truncated = Buffer.concat([b1, b2], 5); console.log(truncated.toString()); // hello `) }) ``` -------------------------------- ### buffer.Enable Source: https://context7.com/dop251/goja_nodejs/llms.txt Injects the `Buffer` global into a runtime, making it available for use. ```APIDOC ## buffer — Buffer Module ### buffer.Enable Injects the `Buffer` global into a runtime (equivalent to calling `require("buffer").Buffer`). ```go import ( "github.com/dop251/goja" "github.com/dop251/goja_nodejs/buffer" "github.com/dop251/goja_nodejs/require" ) registry := require.NewRegistry() rt := goja.New() registry.Enable(rt) buffer.Enable(rt) // Buffer is now a global rt.RunString(` var b = Buffer.from("hello", "utf8"); console.log(b.toString("hex")); // 68656c6c6f console.log(b.toString("base64")); // aGVsbG8= console.log(b.length); // 5 `) ``` ``` -------------------------------- ### Enable console module with custom Printer Source: https://context7.com/dop251/goja_nodejs/llms.txt Enables the console module with a custom Printer implementation for controlled log output redirection. ```go type BufferPrinter struct { Buf []string } func (p *BufferPrinter) Log(s string) { p.Buf = append(p.Buf, "LOG:"+s) } func (p *BufferPrinter) Warn(s string) { p.Buf = append(p.Buf, "WARN:"+s) } func (p *BufferPrinter) Error(s string) { p.Buf = append(p.Buf, "ERR:"+s) } printer := &BufferPrinter{} registry := require.NewRegistry() registry.RegisterNativeModule(console.ModuleName, console.RequireWithPrinter(printer)) rt := goja.New() registry.Enable(rt) console.Enable(rt) rt.RunString(`console.log("test"); console.error("fail");`) fmt.Println(printer.Buf) // [LOG:test ERR:fail] ``` -------------------------------- ### Require (package-level helper) Source: https://context7.com/dop251/goja_nodejs/llms.txt Convenience function that calls the runtime's require() directly. Panics if require is not enabled on the runtime. ```APIDOC ## Require (package-level helper) ### Description Convenience function that calls the runtime's `require()` directly. Panics if `require` is not enabled on the runtime. ### Usage Example ```go registry := require.NewRegistry() rt := goja.New() registry.Enable(rt) // Require a built-in core module from Go utilExports := require.Require(rt, "util") println(utilExports) // [object Object] ``` ``` -------------------------------- ### Registry.Enable Source: https://context7.com/dop251/goja_nodejs/llms.txt Attaches a require() function to a specific goja.Runtime and returns a *RequireModule handle. Must be called before any JS code runs require(). ```APIDOC ## Registry.Enable ### Description Attaches a `require()` function to a specific `goja.Runtime` and returns a `*RequireModule` handle. Must be called before any JS code runs `require()`. ### Usage Example ```go registry := require.NewRegistry() rt1 := goja.New() rt2 := goja.New() req1 := registry.Enable(rt1) // rt1 now has require() req2 := registry.Enable(rt2) // rt2 now has require(); compiled cache shared // Load a module from Go code on rt1 exports, err := req1.Require("./config.js") if err != nil { panic(err) } _ = req2 println(exports) // module exports object ``` ``` -------------------------------- ### URLSearchParams (JS API) Source: https://context7.com/dop251/goja_nodejs/llms.txt Full implementation of the WHATWG URLSearchParams interface, including iterators. Ensure require.Registry and url.Enable are called. ```go registry := require.NewRegistry() rt := goja.New() registry.Enable(rt) url.Enable(rt) rt.RunString( "\n // Construct from string\n var sp = new URLSearchParams(\"a=1&b=2&a=3\");\n console.log(sp.get(\"a\")); // 1\n console.log(sp.getAll(\"a\")); // [\"1\",\"3\"]\n console.log(sp.has(\"b\")); // true\n console.log(sp.size); // 3\n\n // Mutate\n sp.append(\"c\", \"4\");\n sp.set(\"a\", \"99\"); // replaces all \"a\" entries\n sp.delete(\"b\");\n\n console.log(sp.toString()); // a=99&a=3&c=4 (first set + remaining)\n\n // Sort by key (stable)\n sp.sort();\n console.log(sp.toString()); // a=99&a=3&c=4 (sorted)\n\n // Iteration\n for (var [k, v] of sp.entries()) {\n console.log(k + \"=\" + v);\n }\n for (var key of sp.keys()) { console.log(key); }\n for (var val of sp.values()) { console.log(val); }\n\n // forEach\n sp.forEach(function(name, value) {\n console.log(name + ":", value);\n });\n\n // Construct from object / array of pairs\n var sp2 = new URLSearchParams({x: \"10\", y: \"20\"});\n console.log(sp2.toString()); // x=10&y=20\n\n var sp3 = new URLSearchParams([[\"m\",\"1\"],[\"n\",\"2\"]]);\n console.log(sp3.toString()); // m=1&n=2\n\n // searchParams on a URL object stays in sync\n var u = new URL(\"https://example.com?foo=bar\");\n u.searchParams.append(\"baz\", \"qux\");\n console.log(u.search); // ?foo=bar&baz=qux\n") ``` -------------------------------- ### Inject URL and URLSearchParams Globals Source: https://context7.com/dop251/goja_nodejs/llms.txt Injects URL and URLSearchParams globals into a runtime without requiring an explicit require("url") in JS. Ensure require.Registry is enabled. ```go import ( "github.com/dop251/goja" "github.com/dop251/goja_nodejs/require" "github.com/dop251/goja_nodejs/url" ) registry := require.NewRegistry() rt := goja.New() registry.Enable(rt) url.Enable(rt) // URL and URLSearchParams are now globals rt.RunString( "\n var u = new URL(\"https://example.com:8080/path?q=1#frag\");\n console.log(u.host); // example.com:8080\n console.log(u.hostname); // example.com\n console.log(u.port); // 8080\n console.log(u.pathname); // /path\n console.log(u.search); // ?q=1\n console.log(u.hash); // #frag\n console.log(u.origin); // https://example.com\n\n // Mutation\n u.pathname = \"/newpath\";\n u.port = \"9090\";\n console.log(u.href); // https://example.com:9090/newpath?q=1#frag\n") ``` -------------------------------- ### url.Enable Source: https://context7.com/dop251/goja_nodejs/llms.txt Injects `URL` and `URLSearchParams` globals into a goja runtime, making them available without explicit requires in JavaScript. ```APIDOC ## url.Enable Injects `URL` and `URLSearchParams` globals into a runtime without requiring an explicit `require("url")` in JS. ```go import ( "github.com/dop251/goja" "github.com/dop251/goja_nodejs/require" "github.com/dop251/goja_nodejs/url" ) registry := require.NewRegistry() rt := goja.New() registry.Enable(rt) url.Enable(rt) // URL and URLSearchParams are now globals rt.RunString(` var u = new URL("https://example.com:8080/path?q=1#frag"); console.log(u.host); // example.com:8080 console.log(u.hostname); // example.com console.log(u.port); // 8080 console.log(u.pathname); // /path console.log(u.search); // ?q=1 console.log(u.hash); // #frag console.log(u.origin); // https://example.com // Mutation u.pathname = "/newpath"; u.port = "9090"; console.log(u.href); // https://example.com:9090/newpath?q=1#frag `) ``` ``` -------------------------------- ### Register Native Module Globally Source: https://context7.com/dop251/goja_nodejs/llms.txt Registers a native module globally, making it available to every `Registry` instance. This is typically called from a package's `init()` function and is not safe for concurrent calls with `require()`. ```go func init() { require.RegisterNativeModule("mylib/crypto", func(rt *goja.Runtime, module *goja.Object) { exports := module.Get("exports").(*goja.Object) exports.Set("randomHex", func(n int) string { b := make([]byte, n) _, _ = rand.Read(b) return hex.EncodeToString(b) }) }) } ``` -------------------------------- ### RegisterNativeModule (global) Source: https://context7.com/dop251/goja_nodejs/llms.txt Registers a native module globally so that every Registry instance can load it. Call from a package init() function; not safe to call concurrently with require(). ```APIDOC ## RegisterNativeModule (global) ### Description Registers a native module globally so that every `Registry` instance can load it. Call from a package `init()` function; not safe to call concurrently with `require()`. ### Usage Example ```go func init() { require.RegisterNativeModule("mylib/crypto", func(rt *goja.Runtime, module *goja.Object) { exports := module.Get("exports").(*goja.Object) exports.Set("randomHex", func(n int) string { b := make([]byte, n) _, _ = rand.Read(b) return hex.EncodeToString(b) }) }) } ``` ``` -------------------------------- ### Require Built-in Core Module from Go Source: https://context7.com/dop251/goja_nodejs/llms.txt A convenience function that directly calls the runtime's `require()` method. It panics if `require` has not been enabled on the runtime. Useful for importing core modules from Go. ```go registry := require.NewRegistry() rt := goja.New() registry.Enable(rt) // Require a built-in core module from Go utilExports := require.Require(rt, "util") println(utilExports) // [object Object] ``` -------------------------------- ### RequireModule.Require Source: https://context7.com/dop251/goja_nodejs/llms.txt Imports a module from Go code after the registry has been enabled on a runtime. Returns the module's exports value. ```APIDOC ## RequireModule.Require ### Description Imports a module from Go code after the registry has been enabled on a runtime. Returns the module's `exports` value. ### Usage Example ```go registry := require.NewRegistry() rt := goja.New() req := registry.Enable(rt) // Load a JSON file (automatically parsed) cfg, err := req.Require("./config.json") if err != nil { log.Fatalf("load config: %v", err) } cfgObj := cfg.ToObject(rt) println(cfgObj.Get("port").ToInteger()) // e.g. 8080 ``` ``` -------------------------------- ### Wrap Go Bytes to JS Buffer and Extract Bytes Source: https://context7.com/dop251/goja_nodejs/llms.txt Use `buffer.WrapBytes` to convert a Go `[]byte` to a JavaScript Buffer. Use `buffer.Bytes` to extract raw bytes from a JavaScript Buffer value. ```go registry := require.NewRegistry() rt := goja.New() registry.Enable(rt) buffer.Enable(rt) // Wrap a Go []byte as a JS Buffer data := []byte{0xDE, 0xAD, 0xBE, 0xEF} jsBuffer := buffer.WrapBytes(rt, data) rt.Set("buf", jsBuffer) rt.RunString(`console.log(buf.toString("hex")); // deadbeef`) // Extract raw bytes from a JS Buffer value rt.RunString(`var out = Buffer.from("AAEC", "base64");`) outVal := rt.Get("out") raw := buffer.Bytes(rt, outVal) fmt.Printf("%v\n", raw) // [0 1 2] ``` -------------------------------- ### Create New EventLoop Source: https://context7.com/dop251/goja_nodejs/llms.txt Creates a new `EventLoop` with its own `goja.Runtime`. Functional options can be provided to customize its behavior, such as sharing an existing registry or disabling the console. ```go import ( "github.com/dop251/goja_nodejs/eventloop" "github.com/dop251/goja_nodejs/require" ) // Default loop (console enabled, fresh Registry) loop := eventloop.NewEventLoop() // Custom loop: share an existing registry, disable console reg := require.NewRegistry() loop2 := eventloop.NewEventLoop( eventloop.WithRegistry(reg), eventloop.EnableConsole(false), ) _ = loop2 ``` -------------------------------- ### Enable require() on a goja.Runtime Source: https://context7.com/dop251/goja_nodejs/llms.txt Attaches a `require()` function to a `goja.Runtime`. Must be called before any JavaScript code attempts to use `require()`. This enables module loading for the runtime. ```go registry := require.NewRegistry() rt1 := goja.New() rt2 := goja.New() req1 := registry.Enable(rt1) // rt1 now has require() req2 := registry.Enable(rt2) // rt2 now has require(); compiled cache shared // Load a module from Go code on rt1 exports, err := req1.Require("./config.js") if err != nil { panic(err) } _ = req2 println(exports) // module exports object ``` -------------------------------- ### Registry.RegisterNativeModule Source: https://context7.com/dop251/goja_nodejs/llms.txt Registers a Go-implemented module with a specific Registry instance. Takes precedence over file-system modules with the same name. ```APIDOC ## Registry.RegisterNativeModule ### Description Registers a Go-implemented module with a specific `Registry` instance. Takes precedence over file-system modules with the same name. ### Usage Example ```go registry := require.NewRegistry() // Register a Go module that exposes a "greet" function registry.RegisterNativeModule("myapp/greeter", func(rt *goja.Runtime, module *goja.Object) { exports := module.Get("exports").(*goja.Object) exports.Set("greet", func(name string) string { return "Hello, " + name + "!" }) }) rt := goja.New() registry.Enable(rt) v, _ := rt.RunString(` var g = require("myapp/greeter"); g.greet("World"); // => "Hello, World!" `) println(v.String()) // Hello, World! ``` ``` -------------------------------- ### JavaScript Buffer Read/Write Integer Methods Source: https://context7.com/dop251/goja_nodejs/llms.txt Illustrates the complete set of typed read/write methods on JavaScript `Buffer` instances, mirroring Node.js. This includes methods for writing and reading various integer types (UInt8, Int16BE/LE, UInt32BE/LE, BigInt64BE) and floating-point numbers (FloatBE), as well as variable-length integer operations and buffer equality checks. ```javascript loop := eventloop.NewEventLoop() loop.Run(func(vm *goja.Runtime) { vm.RunString(` var buf = Buffer.alloc(16); // Write various types buf.writeUInt8(255, 0); buf.writeInt16BE(-1000, 1); buf.writeInt16LE(-1000, 3); buf.writeUInt32BE(0xDEADBEEF, 5); buf.writeUInt32LE(0xDEADBEEF, 9); buf.writeFloatBE(3.14, 13); // offset 13, 4 bytes // Read them back console.log(buf.readUInt8(0)); // 255 console.log(buf.readInt16BE(1)); // -1000 console.log(buf.readInt16LE(3)); // -1000 console.log(buf.readUInt32BE(5).toString(16)); // deadbeef console.log(buf.readUInt32LE(9).toString(16)); // deadbeef console.log(buf.readFloatBE(13).toFixed(2)); // 3.14 // 64-bit integers using BigInt var bigBuf = Buffer.alloc(8); bigBuf.writeBigInt64BE(BigInt("-9007199254740992"), 0); console.log(bigBuf.readBigInt64BE(0).toString()); // -9007199254740992 // Variable-length read/write (1-6 bytes) var vbuf = Buffer.alloc(6); vbuf.writeIntBE(0x123456, 0, 3); console.log(vbuf.readIntBE(0, 3).toString(16)); // 123456 // equals var a = Buffer.from("abc"); var b = Buffer.from("abc"); console.log(a.equals(b)); // true `) }) ``` -------------------------------- ### URL constructor (JS API) Source: https://context7.com/dop251/goja_nodejs/llms.txt The `URL` constructor in JavaScript supports absolute URL construction, base-relative resolution, and IDNA (Punycode) hostname normalization. ```APIDOC ## URL constructor (JS API) Supports both absolute URL construction and base-relative resolution, with IDNA (Punycode) hostname normalisation. ```go registry := require.NewRegistry() rt := goja.New() registry.Enable(rt) url.Enable(rt) rt.RunString(` // Relative URL resolved against a base var base = new URL("https://example.com/a/b/"); var rel = new URL("../c", base); console.log(rel.href); // https://example.com/a/c // IDNA hostname normalisation var idn = new URL("https://\u4e2d\u6587.com/path"); console.log(idn.hostname); // xn--fiq228c.com (Punycode) // Credentials in URL var auth = new URL("https://user:pass@secure.example.com/"); console.log(auth.username); // user console.log(auth.password); // pass // toString / toJSON console.log(rel.toString()); // https://example.com/a/c console.log(JSON.stringify(rel)); // "https://example.com/a/c" // Invalid URL throws try { new URL("not a url"); } catch(e) { console.log(e.code); // ERR_INVALID_URL } `) ``` ``` -------------------------------- ### util.New / Util.Format Source: https://context7.com/dop251/goja_nodejs/llms.txt Provides Go-side utility functions for formatting strings, including support for string, number, JSON, and literal percent characters. ```APIDOC ## util — Util Module ### util.New / Util.Format `util.New` creates a Go-side `Util` instance; `Format` renders a printf-style format string using `%s` (string), `%d` (number), `%j` (JSON), and `%%` (literal `%`). ```go import ( "bytes" "fmt" "github.com/dop251/goja" "github.com/dop251/goja_nodejs/require" "github.com/dop251/goja_nodejs/util" ) registry := require.NewRegistry() rt := goja.New() registry.Enable(rt) u := util.New(rt) var buf bytes.Buffer u.Format(&buf, "hello %s, count=%d, data=%j, literal=%%", rt.ToValue("world"), rt.ToValue(42), rt.ToValue(map[string]interface{}{"ok": true}), ) fmt.Println(buf.String()) // hello world, count=42, data={"ok":true}, literal=% // Or use it from JavaScript via require rt.RunString(` var util = require("util"); console.log(util.format("name=%s age=%d info=%j", "Alice", 30, {admin:true})); // name=Alice age=30 info={"admin":true} `) ``` ``` -------------------------------- ### Import Module from Go Code Source: https://context7.com/dop251/goja_nodejs/llms.txt Imports a module from Go code using `RequireModule.Require` after the registry has been enabled on a runtime. This function returns the module's `exports` value and can load various file types, including JSON. ```go registry := require.NewRegistry() rt := goja.New() req := registry.Enable(rt) // Load a JSON file (automatically parsed) cfg, err := req.Require("./config.json") if err != nil { log.Fatalf("load config: %v", err) } cfgObj := cfg.ToObject(rt) println(cfgObj.Get("port").ToInteger()) // e.g. 8080 ``` -------------------------------- ### buffer.WrapBytes / buffer.Bytes Source: https://context7.com/dop251/goja_nodejs/llms.txt Provides Go helper functions to convert between Go byte slices (`[]byte`) and Goja `Buffer` objects. `WrapBytes` converts Go `[]byte` to a JS `Buffer`, and `Bytes` extracts raw bytes from a JS `Buffer` value. ```APIDOC ## buffer.WrapBytes / buffer.Bytes ### Description Go helpers for converting between Go `[]byte` and Goja `Buffer` objects. ### Usage **Wrap a Go `[]byte` as a JS `Buffer`:** ```go data := []byte{0xDE, 0xAD, 0xBE, 0xEF} jsBuffer := buffer.WrapBytes(rt, data) ``` **Extract raw bytes from a JS `Buffer` value:** ```go rt.RunString(`var out = Buffer.from("AAEC", "base64");`) outVal := rt.Get("out") raw := buffer.Bytes(rt, outVal) fmt.Printf("%v\n", raw) // [0 1 2] ``` ``` -------------------------------- ### Register Node.js Core Module Source: https://context7.com/dop251/goja_nodejs/llms.txt Registers a Node.js-style core module, accessible via both its name and `node:name`. This is used internally for modules like buffer, console, url, util, and process. ```go func init() { require.RegisterCoreModule("mycore", func(rt *goja.Runtime, module *goja.Object) { exports := module.Get("exports").(*goja.Object) exports.Set("version", "1.0.0") }) } // In JavaScript: // var c = require("mycore"); // works // var c = require("node:mycore"); // also works ``` -------------------------------- ### Buffer read/write integer methods (JS API) Source: https://context7.com/dop251/goja_nodejs/llms.txt Details the complete set of typed read/write methods available on Buffer instances in JavaScript, mirroring Node.js functionality for handling various integer and float types, including BigInt support and variable-length operations. ```APIDOC ## Buffer read/write integer methods (JS API) ### Description Complete set of typed read/write methods on Buffer instances, mirroring Node.js. ### Usage ```javascript var buf = Buffer.alloc(16); // Write various types buf.writeUInt8(255, 0); buf.writeInt16BE(-1000, 1); buf.writeInt16LE(-1000, 3); buf.writeUInt32BE(0xDEADBEEF, 5); buf.writeUInt32LE(0xDEADBEEF, 9); buf.writeFloatBE(3.14, 13); // offset 13, 4 bytes // Read them back console.log(buf.readUInt8(0)); // 255 console.log(buf.readInt16BE(1)); // -1000 console.log(buf.readInt16LE(3)); // -1000 console.log(buf.readUInt32BE(5).toString(16)); // deadbeef console.log(buf.readUInt32LE(9).toString(16)); // deadbeef console.log(buf.readFloatBE(13).toFixed(2)); // 3.14 // 64-bit integers using BigInt var bigBuf = Buffer.alloc(8); bigBuf.writeBigInt64BE(BigInt("-9007199254740992"), 0); console.log(bigBuf.readBigInt64BE(0).toString()); // -9007199254740992 // Variable-length read/write (1-6 bytes) var vbuf = Buffer.alloc(6); vbuf.writeIntBE(0x123456, 0, 3); console.log(vbuf.readIntBE(0, 3).toString(16)); // 123456 // equals var a = Buffer.from("abc"); var b = Buffer.from("abc"); console.log(a.equals(b)); // true ``` ``` -------------------------------- ### EventLoop SetTimeout and ClearTimeout Source: https://context7.com/dop251/goja_nodejs/llms.txt Provides Go-side equivalents for JavaScript's setTimeout and clearTimeout. Can be used to schedule and cancel function executions. ```go loop := eventloop.NewEventLoop() loop.Start() t := loop.SetTimeout(func(vm *goja.Runtime) { vm.RunString(`console.log("fired after 500ms")`) }, 500*time.Millisecond) // Cancel before it fires loop.ClearTimeout(t) // Also available from JavaScript inside the loop: loop.Run(func(vm *goja.Runtime) { vm.RunString(` var id = setTimeout(function() { console.log("this fires"); }, 100); clearTimeout(id); // cancel it immediately `) }) loop.Terminate() ``` -------------------------------- ### URLSearchParams (JS API) Source: https://context7.com/dop251/goja_nodejs/llms.txt Provides a full implementation of the WHATWG `URLSearchParams` interface, including methods for manipulation and iteration. ```APIDOC ## URLSearchParams (JS API) Full implementation of the WHATWG `URLSearchParams` interface, including iterators. ```go registry := require.NewRegistry() rt := goja.New() registry.Enable(rt) url.Enable(rt) rt.RunString(` // Construct from string var sp = new URLSearchParams("a=1&b=2&a=3"); console.log(sp.get("a")); // 1 console.log(sp.getAll("a")); // ["1","3"] console.log(sp.has("b")); // true console.log(sp.size); // 3 // Mutate sp.append("c", "4"); sp.set("a", "99"); // replaces all "a" entries sp.delete("b"); console.log(sp.toString()); // a=99&a=3&c=4 (first set + remaining) // Sort by key (stable) sp.sort(); console.log(sp.toString()); // a=99&a=3&c=4 (sorted) // Iteration for (var [k, v] of sp.entries()) { console.log(k + "=" + v); } for (var key of sp.keys()) { console.log(key); } for (var val of sp.values()) { console.log(val); } // forEach sp.forEach(function(name, value) { console.log(name + ":", value); }); // Construct from object / array of pairs var sp2 = new URLSearchParams({x: "10", y: "20"}); console.log(sp2.toString()); // x=10&y=20 var sp3 = new URLSearchParams([["m","1"],["n","2"]]); console.log(sp3.toString()); // m=1&n=2 // searchParams on a URL object stays in sync var u = new URL("https://example.com?foo=bar"); u.searchParams.append("baz", "qux"); console.log(u.search); // ?foo=bar&baz=qux `) ``` ``` -------------------------------- ### Enable Process Global in Goja Source: https://context7.com/dop251/goja_nodejs/llms.txt Injects the 'process' global into a Goja runtime, populating 'process.env' from the host's OS environment. This is useful for accessing environment variables within the JavaScript sandbox. ```go import ( "github.com/dop251/goja" "github.com/dop251/goja_nodejs/process" "github.com/dop251/goja_nodejs/require" "os" ) os.Setenv("APP_MODE", "production") registry := require.NewRegistry() rt := goja.New() registry.Enable(rt) process.Enable(rt) // process is now a global rt.RunString( ` console.log(process.env.APP_MODE); // production console.log(typeof process.env.HOME); // string (or undefined on Windows) // process.env is a plain object; keys are all host env vars var keys = Object.keys(process.env); console.log(keys.length); // number of env vars on the host ` ) // Or load as a module rt.RunString( ` var proc = require("process"); // also accessible as "node:process" console.log(proc.env.APP_MODE); // production ` ) ``` -------------------------------- ### EventLoop.Run Source: https://context7.com/dop251/goja_nodejs/llms.txt Runs a function synchronously inside the loop, then processes all pending timers and returns when the queue is empty. ```APIDOC ## EventLoop.Run ### Description Runs a function synchronously inside the loop, then processes all pending timers and returns when the queue is empty. ### Usage Example ```go loop := eventloop.NewEventLoop() loop.Run(func(vm *goja.Runtime) { _, err := vm.RunString(` var results = []; setTimeout(function() { results.push("first"); }, 10); setTimeout(function() { results.push("second"); }, 20); setImmediate(function() { results.push("immediate"); }); `) if err != nil { panic(err) } }) // After Run returns, all three callbacks have fired. ``` ``` -------------------------------- ### EventLoop SetInterval and ClearInterval Source: https://context7.com/dop251/goja_nodejs/llms.txt Provides Go-side equivalents for JavaScript's setInterval and clearInterval. Use to repeatedly execute a function at a fixed interval. ```go loop := eventloop.NewEventLoop() loop.Start() count := 0 interval := loop.SetInterval(func(vm *goja.Runtime) { count++ if count >= 3 { loop.StopNoWait() // stop from within a callback } }, 100*time.Millisecond) // Or cancel from outside time.AfterFunc(1*time.Second, func() { loop.ClearInterval(interval) loop.StopNoWait() }) loop.Terminate() println("fired", count, "times") ``` -------------------------------- ### console.RequireWithPrinter Source: https://context7.com/dop251/goja_nodejs/llms.txt Returns a `ModuleLoader` that uses a custom `Printer` implementation for the console module. ```APIDOC ### console.RequireWithPrinter Returns a `ModuleLoader` that uses a custom `Printer` implementation, allowing full control over where log output goes. ```go type BufferPrinter struct { Buf []string } func (p *BufferPrinter) Log(s string) { p.Buf = append(p.Buf, "LOG:"+s) } func (p *BufferPrinter) Warn(s string) { p.Buf = append(p.Buf, "WARN:"+s) } func (p *BufferPrinter) Error(s string) { p.Buf = append(p.Buf, "ERR:"+s) } printer := &BufferPrinter{} registry := require.NewRegistry() registry.RegisterNativeModule(console.ModuleName, console.RequireWithPrinter(printer)) rt := goja.New() registry.Enable(rt) console.Enable(rt) rt.RunString(`console.log("test"); console.error("fail");`) fmt.Println(printer.Buf) // [LOG:test ERR:fail] ``` ``` -------------------------------- ### RegisterCoreModule Source: https://context7.com/dop251/goja_nodejs/llms.txt Registers a Node.js-style core module (accessible as both "name" and "node:name"). Used internally by buffer, console, url, util, and process. ```APIDOC ## RegisterCoreModule ### Description Registers a Node.js-style core module (accessible as both `"name"` and `"node:name"`). Used internally by buffer, console, url, util, and process. ### Usage Example ```go func init() { require.RegisterCoreModule("mycore", func(rt *goja.Runtime, module *goja.Object) { exports := module.Get("exports").(*goja.Object) exports.Set("version", "1.0.0") }) } // In JavaScript: // var c = require("mycore"); // works // var c = require("node:mycore"); // also works ``` ``` -------------------------------- ### NewEventLoop Source: https://context7.com/dop251/goja_nodejs/llms.txt Creates a new EventLoop with its own goja.Runtime. Accepts functional options. ```APIDOC ## NewEventLoop ### Description Creates a new `EventLoop` with its own `goja.Runtime`. Accepts functional options. ### Usage Example ```go import ( "github.com/dop251/goja_nodejs/eventloop" "github.com/dop251/goja_nodejs/require" ) // Default loop (console enabled, fresh Registry) loop := eventloop.NewEventLoop() // Custom loop: share an existing registry, disable console reg := require.NewRegistry() loop2 := eventloop.NewEventLoop( eventloop.WithRegistry(reg), eventloop.EnableConsole(false), ) _ = loop2 ``` ```