quickjs

package module
v0.5.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 6, 2025 License: MIT Imports: 15 Imported by: 28

README

quickjs-go

English | 简体中文

Test codecov Go Report Card GoDoc FOSSA Status

Go bindings to QuickJS: a fast, small, and embeddable ES2020 JavaScript interpreter.

Platform Support

we prebuilt quickjs static library for the following platforms:

Platform Arch Static Library
Linux x64 libquickjs.a
Linux arm64 libquickjs.a
Windows x64 libquickjs.a
Windows x86 libquickjs.a
MacOS x64 libquickjs.a
MacOS arm64 libquickjs.a

* for build on windows, ples see: https://github.com/buke/quickjs-go/issues/151#issuecomment-2134307728

Version Notes

quickjs-go QuickJS
v0.5.x v2025-04-26
v0.4.x v2024-02-14
v0.3.x v2024-01-13
v0.2.x v2023-12-09
v0.1.x v2021-03-27

Breaking Changes

v0.5.x

Collection API Removal: The main goal of this project is to provide bindings for the QuickJS C API, therefore collection-related APIs have been removed. The following methods are no longer available:

  • ctx.Array() - Use ctx.Eval("[]") or ctx.Object() instead
  • ctx.Map() - Use ctx.Eval("new Map()") instead
  • ctx.Set() - Use ctx.Eval("new Set()") instead
  • value.ToArray() - Use direct Value operations instead
  • value.ToMap() - Use direct Value operations instead
  • value.ToSet() - Use direct Value operations instead
  • value.IsMap() - Use value.GlobalInstanceof("Map") instead
  • value.IsSet() - Use value.GlobalInstanceof("Set") instead

Migration Guide:

// Before (v0.4.x and earlier)
arr := ctx.Array()
arr.Set("0", ctx.String("item"))

mapObj := ctx.Map()
mapObj.Set("key", ctx.String("value"))

setObj := ctx.Set()
setObj.Add(ctx.String("item"))

// After (v0.5.x)
arr, _ := ctx.Eval("[]")
arr.Set("0", ctx.String("item"))
arr.Set("length", ctx.Int32(1))

mapObj, _ := ctx.Eval("new Map()")
mapObj.Call("set", ctx.String("key"), ctx.String("value"))

setObj, _ := ctx.Eval("new Set()")
setObj.Call("add", ctx.String("item"))

Features

  • Evaluate script
  • Compile script into bytecode and Eval from bytecode
  • Operate JavaScript values and objects in Go
  • Bind Go function to JavaScript async/sync function
  • Simple exception throwing and catching
  • Marshal/Unmarshal Go values to/from JavaScript values
  • Full TypedArray support (Int8Array, Uint8Array, Float32Array, etc.)

Guidelines

  1. Free quickjs.Runtime and quickjs.Context once you are done using them.
  2. Free quickjs.Value's returned by Eval() and EvalFile(). All other values do not need to be freed, as they get garbage-collected.
  3. Use ctx.Loop() wait for promise/job result after you using promise/job
  4. You may access the stacktrace of an error returned by Eval() or EvalFile() by casting it to a *quickjs.Error.
  5. Make new copies of arguments should you want to return them in functions you created.

Usage

import "github.com/buke/quickjs-go"
Run a script
package main

import (
    "fmt"

    "github.com/buke/quickjs-go"
)

func main() {
    // Create a new runtime
    rt := quickjs.NewRuntime(
        quickjs.WithExecuteTimeout(30),
        quickjs.WithMemoryLimit(128*1024),
        quickjs.WithGCThreshold(256*1024),
        quickjs.WithMaxStackSize(65534),
        quickjs.WithCanBlock(true),
    )
    defer rt.Close()

    // Create a new context
    ctx := rt.NewContext()
    defer ctx.Close()

    ret, err := ctx.Eval("'Hello ' + 'QuickJS!'")
    if err != nil {
        println(err.Error())
    }
    fmt.Println(ret.String())
}
Get/Set Javascript Object
package main

import (
    "fmt"

    "github.com/buke/quickjs-go"
)

func main() {
    // Create a new runtime
    rt := quickjs.NewRuntime()
    defer rt.Close()

    // Create a new context
    ctx := rt.NewContext()
    defer ctx.Close()

    test := ctx.Object()
    test.Set("A", ctx.String("String A"))
    test.Set("B", ctx.String("String B"))
    test.Set("C", ctx.String("String C"))
    ctx.Globals().Set("test", test)

    ret, _ := ctx.Eval(`Object.keys(test).map(key => test[key]).join(" ")`)
    defer ret.Free()
    fmt.Println(ret.String())
}

Bind Go Funtion to Javascript async/sync function
package main
import "github.com/buke/quickjs-go"

func main() {
    // Create a new runtime
    rt := quickjs.NewRuntime()
    defer rt.Close()

    // Create a new context
    ctx := rt.NewContext()
    defer ctx.Close()

    // Create a new object
    test := ctx.Object()
    defer test.Free()
    // bind properties to the object
    test.Set("A", test.Context().String("String A"))
    test.Set("B", ctx.Int32(0))
    test.Set("C", ctx.Bool(false))
    // bind go function to js object
    test.Set("hello", ctx.Function(func(ctx *quickjs.Context, this quickjs.Value, args []quickjs.Value) quickjs.Value {
        return ctx.String("Hello " + args[0].String())
    }))

    // bind "test" object to global object
    ctx.Globals().Set("test", test)

    // call js function by js
    js_ret, _ := ctx.Eval(`test.hello("Javascript!")`)
    fmt.Println(js_ret.String())

    // call js function by go
    go_ret := ctx.Globals().Get("test").Call("hello", ctx.String("Golang!"))
    fmt.Println(go_ret.String())

    // bind go function to Javascript async function using Function + Promise
    ctx.Globals().Set("testAsync", ctx.Function(func(ctx *quickjs.Context, this quickjs.Value, args []quickjs.Value) quickjs.Value {
        return ctx.Promise(func(resolve, reject func(quickjs.Value)) {
            resolve(ctx.String("Hello Async Function!"))
        })
    }))

    ret, _ := ctx.Eval(`
            var ret;
            testAsync().then(v => ret = v)
        `)
    defer ret.Free()

    // wait for promise resolve
    ctx.Loop()

    //get promise result
    asyncRet, _ := ctx.Eval("ret")
    defer asyncRet.Free()

    fmt.Println(asyncRet.String())

    // Output:
    // Hello Javascript!
    // Hello Golang!
    // Hello Async Function!
}
Error Handling
package main

import (
    "fmt"

    "github.com/buke/quickjs-go"
)

func main() {
    // Create a new runtime
    rt := quickjs.NewRuntime()
    defer rt.Close()

    // Create a new context
    ctx := rt.NewContext()
    defer ctx.Close()

    ctx.Globals().SetFunction("A", func(ctx *Context, this Value, args []Value) Value {
        // raise error
        return ctx.ThrowError(expected)
    })

    _, actual := ctx.Eval("A()")
    fmt.Println(actual.Error())
}
TypedArray Support

QuickJS-Go provides full support for JavaScript TypedArrays, enabling efficient binary data processing between Go and JavaScript.

Creating TypedArrays from Go
package main

import (
    "fmt"
    "github.com/buke/quickjs-go"
)

func main() {
    rt := quickjs.NewRuntime()
    defer rt.Close()
    ctx := rt.NewContext()
    defer ctx.Close()

    // Create various TypedArrays from Go slices
    int8Data := []int8{-128, -1, 0, 1, 127}
    int8Array := ctx.Int8Array(int8Data)
    defer int8Array.Free()

    uint8Data := []uint8{0, 128, 255}
    uint8Array := ctx.Uint8Array(uint8Data)
    defer uint8Array.Free()

    float32Data := []float32{-3.14, 0.0, 2.718, 100.5}
    float32Array := ctx.Float32Array(float32Data)
    defer float32Array.Free()

    int64Data := []int64{-9223372036854775808, 0, 9223372036854775807}
    bigInt64Array := ctx.BigInt64Array(int64Data)
    defer bigInt64Array.Free()

    // Set TypedArrays as global variables
    ctx.Globals().Set("int8Array", int8Array)
    ctx.Globals().Set("uint8Array", uint8Array)
    ctx.Globals().Set("float32Array", float32Array)
    ctx.Globals().Set("bigInt64Array", bigInt64Array)

    // Use in JavaScript
    result, _ := ctx.Eval(`
        // Check types
        const results = {
            int8Type: int8Array instanceof Int8Array,
            uint8Type: uint8Array instanceof Uint8Array,
            float32Type: float32Array instanceof Float32Array,
            bigInt64Type: bigInt64Array instanceof BigInt64Array,
            // Calculate sum of float32 array
            float32Sum: float32Array.reduce((sum, val) => sum + val, 0)
        };
        results;
    `)
    defer result.Free()

    fmt.Println("Results:", result.JSONStringify())
}
Converting JavaScript TypedArrays to Go
package main

import (
    "fmt"
    "github.com/buke/quickjs-go"
)

func main() {
    rt := quickjs.NewRuntime()
    defer rt.Close()
    ctx := rt.NewContext()
    defer ctx.Close()

    // Create TypedArrays in JavaScript
    jsTypedArrays, _ := ctx.Eval(`
        ({
            int8: new Int8Array([-128, -1, 0, 1, 127]),
            uint16: new Uint16Array([0, 32768, 65535]),
            float64: new Float64Array([Math.PI, Math.E, 42.5]),
            bigUint64: new BigUint64Array([0n, 18446744073709551615n])
        })
    `)
    defer jsTypedArrays.Free()

    // Convert to Go slices
    int8Array := jsTypedArrays.Get("int8")
    defer int8Array.Free()
    if int8Array.IsInt8Array() {
        goInt8Slice, err := int8Array.ToInt8Array()
        if err == nil {
            fmt.Printf("Int8Array: %v\n", goInt8Slice)
        }
    }

    uint16Array := jsTypedArrays.Get("uint16")
    defer uint16Array.Free()
    if uint16Array.IsUint16Array() {
        goUint16Slice, err := uint16Array.ToUint16Array()
        if err == nil {
            fmt.Printf("Uint16Array: %v\n", goUint16Slice)
        }
    }

    float64Array := jsTypedArrays.Get("float64")
    defer float64Array.Free()
    if float64Array.IsFloat64Array() {
        goFloat64Slice, err := float64Array.ToFloat64Array()
        if err == nil {
            fmt.Printf("Float64Array: %v\n", goFloat64Slice)
        }
    }

    bigUint64Array := jsTypedArrays.Get("bigUint64")
    defer bigUint64Array.Free()
    if bigUint64Array.IsBigUint64Array() {
        goBigUint64Slice, err := bigUint64Array.ToBigUint64Array()
        if err == nil {
            fmt.Printf("BigUint64Array: %v\n", goBigUint64Slice)
        }
    }
}
TypedArray Types Support
Go Type JavaScript TypedArray Context Method Value Method
[]int8 Int8Array ctx.Int8Array() val.ToInt8Array()
[]uint8 Uint8Array ctx.Uint8Array() val.ToUint8Array()
[]uint8 Uint8ClampedArray ctx.Uint8ClampedArray() val.ToUint8Array()
[]int16 Int16Array ctx.Int16Array() val.ToInt16Array()
[]uint16 Uint16Array ctx.Uint16Array() val.ToUint16Array()
[]int32 Int32Array ctx.Int32Array() val.ToInt32Array()
[]uint32 Uint32Array ctx.Uint32Array() val.ToUint32Array()
[]float32 Float32Array ctx.Float32Array() val.ToFloat32Array()
[]float64 Float64Array ctx.Float64Array() val.ToFloat64Array()
[]int64 BigInt64Array ctx.BigInt64Array() val.ToBigInt64Array()
[]uint64 BigUint64Array ctx.BigUint64Array() val.ToBigUint64Array()
[]byte ArrayBuffer ctx.ArrayBuffer() val.ToByteArray()
TypedArray Detection
package main

import (
    "fmt"
    "github.com/buke/quickjs-go"
)

func main() {
    rt := quickjs.NewRuntime()
    defer rt.Close()
    ctx := rt.NewContext()
    defer ctx.Close()

    // Create various arrays
    regularArray, _ := ctx.Eval(`[1, 2, 3]`)
    defer regularArray.Free()

    int32Array := ctx.Int32Array([]int32{1, 2, 3})
    defer int32Array.Free()

    float64Array := ctx.Float64Array([]float64{1.1, 2.2, 3.3})
    defer float64Array.Free()

    // Detect array types
    fmt.Printf("Regular array IsArray: %v\n", regularArray.IsArray())
    fmt.Printf("Regular array IsTypedArray: %v\n", regularArray.IsTypedArray())

    fmt.Printf("Int32Array IsTypedArray: %v\n", int32Array.IsTypedArray())
    fmt.Printf("Int32Array IsInt32Array: %v\n", int32Array.IsInt32Array())
    fmt.Printf("Int32Array IsFloat64Array: %v\n", int32Array.IsFloat64Array())

    fmt.Printf("Float64Array IsTypedArray: %v\n", float64Array.IsTypedArray())
    fmt.Printf("Float64Array IsFloat64Array: %v\n", float64Array.IsFloat64Array())
    fmt.Printf("Float64Array IsInt32Array: %v\n", float64Array.IsInt32Array())
}
Binary Data Processing Example
package main

import (
    "fmt"
    "github.com/buke/quickjs-go"
)

func main() {
    rt := quickjs.NewRuntime()
    defer rt.Close()
    ctx := rt.NewContext()
    defer ctx.Close()

    // Process image-like data (simulate RGB pixels)
    imageData := []uint8{
        255, 0, 0,    // Red pixel
        0, 255, 0,    // Green pixel  
        0, 0, 255,    // Blue pixel
        255, 255, 0,  // Yellow pixel
    }

    // Send to JavaScript as Uint8Array
    imageArray := ctx.Uint8Array(imageData)
    ctx.Globals().Set("imageData", imageArray)

    // Process in JavaScript
    result, _ := ctx.Eval(`
        // Convert RGB to grayscale
        const grayscale = new Uint8Array(imageData.length / 3);
        for (let i = 0; i < imageData.length; i += 3) {
            const r = imageData[i];
            const g = imageData[i + 1];
            const b = imageData[i + 2];
            grayscale[i / 3] = Math.round(0.299 * r + 0.587 * g + 0.114 * b);
        }
        grayscale;
    `)
    defer result.Free()

    // Convert back to Go
    if result.IsUint8Array() {
        grayscaleData, err := result.ToUint8Array()
        if err == nil {
            fmt.Printf("Original RGB: %v\n", imageData)
            fmt.Printf("Grayscale: %v\n", grayscaleData)
        }
    }
}
Marshal/Unmarshal Go Values

QuickJS-Go provides seamless conversion between Go and JavaScript values through the Marshal and Unmarshal methods.

Basic Types
package main

import (
    "fmt"
    "github.com/buke/quickjs-go"
)

func main() {
    rt := quickjs.NewRuntime()
    defer rt.Close()
    ctx := rt.NewContext()
    defer ctx.Close()

    // Marshal Go values to JavaScript
    data := map[string]interface{}{
        "name":    "John Doe",
        "age":     30,
        "active":  true,
        "scores":  []int{85, 92, 78},
        "address": map[string]string{
            "city":    "New York",
            "country": "USA",
        },
        // TypedArray will be automatically created for typed slices
        "floatData": []float32{1.1, 2.2, 3.3},
        "intData":   []int32{100, 200, 300},
        "byteData":  []byte{0x48, 0x65, 0x6C, 0x6C, 0x6F}, // "Hello" in bytes
    }

    jsVal, err := ctx.Marshal(data)
    if err != nil {
        panic(err)
    }
    defer jsVal.Free()

    // Use the marshaled value in JavaScript
    ctx.Globals().Set("user", jsVal)
    result, _ := ctx.Eval(`
        const info = user.name + " is " + user.age + " years old";
        const floatArrayType = user.floatData instanceof Float32Array;
        const intArrayType = user.intData instanceof Int32Array;
        const byteArrayType = user.byteData instanceof ArrayBuffer;
        
        ({
            info: info,
            floatArrayType: floatArrayType,
            intArrayType: intArrayType,
            byteArrayType: byteArrayType,
            byteString: new TextDecoder().decode(user.byteData)
        });
    `)
    defer result.Free()
    fmt.Println("Result:", result.JSONStringify())

    // Unmarshal JavaScript values back to Go
    var userData map[string]interface{}
    err = ctx.Unmarshal(jsVal, &userData)
    if err != nil {
        panic(err)
    }
    fmt.Printf("Unmarshaled: %+v\n", userData)
}
Struct Marshaling with Tags
package main

import (
    "fmt"
    "time"
    "github.com/buke/quickjs-go"
)

type User struct {
    ID        int64     `js:"id"`
    Name      string    `js:"name"`
    Email     string    `json:"email_address"`
    CreatedAt time.Time `js:"created_at"`
    IsActive  bool      `js:"is_active"`
    Tags      []string  `js:"tags"`
    // TypedArray fields
    Scores    []float32 `js:"scores"`    // Will become Float32Array
    Data      []int32   `js:"data"`      // Will become Int32Array
    Binary    []byte    `js:"binary"`    // Will become ArrayBuffer
    // unexported fields are ignored
    password  string
    // Fields with "-" tag are skipped
    Secret    string `js:"-"`
}

func main() {
    rt := quickjs.NewRuntime()
    defer rt.Close()
    ctx := rt.NewContext()
    defer ctx.Close()

    user := User{
        ID:        123,
        Name:      "Alice",
        Email:     "alice@example.com",
        CreatedAt: time.Now(),
        IsActive:  true,
        Tags:      []string{"admin", "user"},
        Scores:    []float32{95.5, 87.2, 92.0},
        Data:      []int32{1000, 2000, 3000},
        Binary:    []byte{0x41, 0x42, 0x43}, // "ABC"
        password:  "secret123",
        Secret:    "top-secret",
    }

    // Marshal struct to JavaScript
    jsVal, err := ctx.Marshal(user)
    if err != nil {
        panic(err)
    }
    defer jsVal.Free()

    // Check TypedArray types in JavaScript
    ctx.Globals().Set("user", jsVal)
    result, _ := ctx.Eval(`
        ({
            scoresType: user.scores instanceof Float32Array,
            dataType: user.data instanceof Int32Array,
            binaryType: user.binary instanceof ArrayBuffer,
            binaryString: new TextDecoder().decode(user.binary),
            avgScore: user.scores.reduce((sum, score) => sum + score) / user.scores.length
        });
    `)
    defer result.Free()
    fmt.Println("TypedArray info:", result.JSONStringify())

    // Modify in JavaScript
    modifyResult, _ := ctx.Eval(`
        user.name = "Alice Smith";
        user.tags.push("moderator");
        // Modify TypedArray data
        user.scores[0] = 98.5;
        user;
    `)
    defer modifyResult.Free()

    // Unmarshal back to Go struct
    var updatedUser User
    err = ctx.Unmarshal(modifyResult, &updatedUser)
    if err != nil {
        panic(err)
    }

    fmt.Printf("Updated user: %+v\n", updatedUser)
    // Note: password and Secret fields remain unchanged (not serialized)
}
Custom Marshal/Unmarshal
package main

import (
    "fmt"
    "strings"
    "github.com/buke/quickjs-go"
)

type CustomType struct {
    Value string
}

// Implement Marshaler interface
func (c CustomType) MarshalJS(ctx *quickjs.Context) (quickjs.Value, error) {
    return ctx.String("custom:" + c.Value), nil
}

// Implement Unmarshaler interface
func (c *CustomType) UnmarshalJS(ctx *quickjs.Context, val quickjs.Value) error {
    if val.IsString() {
        str := val.ToString()
        if strings.HasPrefix(str, "custom:") {
            c.Value = str[7:] // Remove "custom:" prefix
        } else {
            c.Value = str
        }
    }
    return nil
}

func main() {
    rt := quickjs.NewRuntime()
    defer rt.Close()
    ctx := rt.NewContext()
    defer ctx.Close()

    // Marshal custom type
    custom := CustomType{Value: "hello"}
    jsVal, err := ctx.Marshal(custom)
    if err != nil {
        panic(err)
    }
    defer jsVal.Free()

    fmt.Println("Marshaled:", jsVal.String()) // Output: custom:hello

    // Unmarshal back
    var result CustomType
    err = ctx.Unmarshal(jsVal, &result)
    if err != nil {
        panic(err)
    }
    fmt.Printf("Unmarshaled: %+v\n", result) // Output: {Value:hello}
}
Type Mappings

Go to JavaScript:

  • bool → JavaScript boolean
  • int, int8, int16, int32 → JavaScript number (32-bit)
  • int64 → JavaScript number (64-bit)
  • uint, uint8, uint16, uint32 → JavaScript number (32-bit unsigned)
  • uint64 → JavaScript BigInt
  • float32, float64 → JavaScript number
  • string → JavaScript string
  • []byte → JavaScript ArrayBuffer
  • []int8 → JavaScript Int8Array
  • []uint8 → JavaScript Uint8Array
  • []int16 → JavaScript Int16Array
  • []uint16 → JavaScript Uint16Array
  • []int32 → JavaScript Int32Array
  • []uint32 → JavaScript Uint32Array
  • []float32 → JavaScript Float32Array
  • []float64 → JavaScript Float64Array
  • []int64 → JavaScript BigInt64Array
  • []uint64 → JavaScript BigUint64Array
  • slice/array → JavaScript Array (for non-typed arrays)
  • map → JavaScript Object
  • struct → JavaScript Object
  • pointer → recursively marshal pointed value (nil becomes null)

JavaScript to Go:

  • JavaScript null/undefined → Go nil pointer or zero value
  • JavaScript boolean → Go bool
  • JavaScript number → Go numeric types (with appropriate conversion)
  • JavaScript BigInt → Go uint64/int64/*big.Int
  • JavaScript string → Go string
  • JavaScript Array → Go slice/array
  • JavaScript Object → Go map/struct
  • JavaScript ArrayBuffer → Go []byte
  • JavaScript Int8Array → Go []int8
  • JavaScript Uint8Array/Uint8ClampedArray → Go []uint8
  • JavaScript Int16Array → Go []int16
  • JavaScript Uint16Array → Go []uint16
  • JavaScript Int32Array → Go []int32
  • JavaScript Uint32Array → Go []uint32
  • JavaScript Float32Array → Go []float32
  • JavaScript Float64Array → Go []float64
  • JavaScript BigInt64Array → Go []int64
  • JavaScript BigUint64Array → Go []uint64

When unmarshaling into interface{}, the following types are used:

  • nil for null/undefined
  • bool for boolean
  • int64 for integer numbers
  • float64 for floating-point numbers
  • string for string
  • []interface{} for Array
  • map[string]interface{} for Object
  • *big.Int for BigInt
  • []byte for ArrayBuffer
Bytecode Compiler

package main

import (
    "fmt"

    "github.com/buke/quickjs-go"
)

func main() {
    // Create a new runtime
    rt := quickjs.NewRuntime()
    defer rt.Close()
    // Create a new context
    ctx := rt.NewContext()
    defer ctx.Close()

    jsStr := `
    function fib(n)
    {
        if (n <= 0)
            return 0;
        else if (n == 1)
            return 1;
        else
            return fib(n - 1) + fib(n - 2);
    }
    fib(10)
    `
    // Compile the script to bytecode
    buf, _ := ctx.Compile(jsStr)

    // Create a new runtime
    rt2 := quickjs.NewRuntime()
    defer rt2.Close()

    // Create a new context
    ctx2 := rt2.NewContext()
    defer ctx2.Close()

    //Eval bytecode
    result, _ := ctx2.EvalBytecode(buf)
    fmt.Println(result.Int32())
}
Runtime Options: memory, stack, GC, ...
package main

import (
    "fmt"

    "github.com/buke/quickjs-go"
)

func main() {
    // Create a new runtime
    rt := quickjs.NewRuntime()
    defer rt.Close()

    // set runtime options
    rt.SetExecuteTimeout(30) // Set execute timeout to 30 seconds
    rt.SetMemoryLimit(256 * 1024) // Set memory limit to 256KB
    rt.SetMaxStackSize(65534) // Set max stack size to 65534
    rt.SetGCThreshold(256 * 1024) // Set GC threshold to 256KB
    rt.SetCanBlock(true) // Set can block to true

    // Create a new context
    ctx := rt.NewContext()
    defer ctx.Close()

    result, err := ctx.Eval(`var array = []; while (true) { array.push(null) }`)
    defer result.Free()
}
ES6 Module Support

package main

import (
    "fmt"

    "github.com/buke/quickjs-go"
)

func main() {
// enable module import
    rt := quickjs.NewRuntime(quickjs.WithModuleImport(true))
    defer rt.Close()

    ctx := rt.NewContext()
    defer ctx.Close()

    // eval module
    r1, err := ctx.EvalFile("./test/hello_module.js")
    defer r1.Free()
    require.NoError(t, err)
    require.EqualValues(t, 55, ctx.Globals().Get("result").Int32())

    // load module
    r2, err := ctx.LoadModuleFile("./test/fib_module.js", "fib_foo")
    defer r2.Free()
    require.NoError(t, err)

    // call module
    r3, err := ctx.Eval(`
    import {fib} from 'fib_foo';
    globalThis.result = fib(9);
    `)
    defer r3.Free()
    require.NoError(t, err)

    require.EqualValues(t, 34, ctx.Globals().Get("result").Int32())
}

Documentation

Go Reference & more examples: https://pkg.go.dev/github.com/buke/quickjs-go

License

MIT

FOSSA Status

Documentation

Overview

Package quickjs Go bindings to QuickJS: a fast, small, and embeddable ES2020 JavaScript interpreter

Example
package main

import (
	"fmt"

	"github.com/buke/quickjs-go"
)

func main() {

	// Create a new runtime
	rt := quickjs.NewRuntime(
		quickjs.WithExecuteTimeout(30),
		quickjs.WithMemoryLimit(128*1024),
		quickjs.WithGCThreshold(256*1024),
		quickjs.WithMaxStackSize(65534),
		quickjs.WithCanBlock(true),
		quickjs.WithStripInfo(1),
	)
	defer rt.Close()

	// Create a new context
	ctx := rt.NewContext()
	defer ctx.Close()

	// Create a new object
	test := ctx.Object()
	defer test.Free()
	// bind properties to the object
	test.Set("A", test.Context().String("String A"))
	test.Set("B", ctx.Int32(0))
	test.Set("C", ctx.Bool(false))
	// bind go function to js object
	test.Set("hello", ctx.Function(func(ctx *quickjs.Context, this quickjs.Value, args []quickjs.Value) quickjs.Value {
		return ctx.String("Hello " + args[0].String())
	}))

	// bind "test" object to global object
	ctx.Globals().Set("test", test)

	// call js function by js
	js_ret, _ := ctx.Eval(`test.hello("Javascript!")`)
	fmt.Println(js_ret.String())

	// call js function by go
	go_ret := ctx.Globals().Get("test").Call("hello", ctx.String("Golang!"))
	fmt.Println(go_ret.String())

	// bind go function to Javascript async function using Function + Promise
	ctx.Globals().Set("testAsync", ctx.Function(func(ctx *quickjs.Context, this quickjs.Value, args []quickjs.Value) quickjs.Value {
		return ctx.Promise(func(resolve, reject func(quickjs.Value)) {
			resolve(ctx.String("Hello Async Function!"))
		})
	}))

	ret, _ := ctx.Eval(`
            var ret;
            testAsync().then(v => ret = v)
        `)
	defer ret.Free()

	// wait for promise resolve
	ctx.Loop()

	asyncRet, _ := ctx.Eval("ret")
	defer asyncRet.Free()

	fmt.Println(asyncRet.String())

}
Output:
Hello Javascript!
Hello Golang!
Hello Async Function!

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Atom

type Atom struct {
	// contains filtered or unexported fields
}

Atom represents a QuickJS atom - unique strings used for object property names. Object property names and some strings are stored as Atoms (unique strings) to save memory and allow fast comparison. Atoms are represented as a 32 bit integer. Half of the atom range is reserved for immediate integer literals from 0 to 2^{31}-1.

func (Atom) Free

func (a Atom) Free()

Free decrements the reference count of the atom.

func (Atom) String

func (a Atom) String() string

String returns the string representation of the atom.

func (Atom) Value

func (a Atom) Value() Value

Value returns the value representation of the atom.

type Context

type Context struct {
	// contains filtered or unexported fields
}

Context represents a Javascript context (or Realm). Each JSContext has its own global objects and system objects. There can be several JSContexts per JSRuntime and they can share objects, similar to frames of the same origin sharing Javascript objects in a web browser.

func (*Context) ArrayBuffer added in v0.1.13

func (ctx *Context) ArrayBuffer(binaryData []byte) Value

ArrayBuffer returns a ArrayBuffer value with given binary data.

func (*Context) AsyncFunction deprecated added in v0.1.2

func (ctx *Context) AsyncFunction(asyncFn func(ctx *Context, this Value, promise Value, args []Value) Value) Value

AsyncFunction returns a js async function value with given function template

Deprecated: Use Context.Function + Context.Promise instead for better memory management and thread safety. Example:

asyncFn := ctx.Function(func(ctx *quickjs.Context, this quickjs.Value, args []quickjs.Value) quickjs.Value {
    return ctx.Promise(func(resolve, reject func(quickjs.Value)) {
        // async work here
        resolve(ctx.String("result"))
    })
})

func (*Context) Atom

func (ctx *Context) Atom(v string) Atom

Atom returns a new Atom value with given string.

func (*Context) AtomIdx

func (ctx *Context) AtomIdx(idx uint32) Atom

Atom returns a new Atom value with given idx.

func (*Context) Await added in v0.4.8

func (ctx *Context) Await(v Value) (Value, error)

Wait for a promise and execute pending jobs while waiting for it. Return the promise result or JS_EXCEPTION in case of promise rejection.

func (*Context) BigInt64

func (ctx *Context) BigInt64(v int64) Value

BigInt64 returns a int64 value with given uint64.

func (*Context) BigInt64Array added in v0.5.4

func (ctx *Context) BigInt64Array(data []int64) Value

BigInt64Array returns a BigInt64Array value with given int64 slice.

func (*Context) BigUint64

func (ctx *Context) BigUint64(v uint64) Value

BigUint64 returns a uint64 value with given uint64.

func (*Context) BigUint64Array added in v0.5.4

func (ctx *Context) BigUint64Array(data []uint64) Value

BigUint64Array returns a BigUint64Array value with given uint64 slice.

func (*Context) Bool

func (ctx *Context) Bool(b bool) Value

Bool returns a bool value with given bool.

func (*Context) Close

func (ctx *Context) Close()

Free will free context and all associated objects.

func (*Context) Compile

func (ctx *Context) Compile(code string, opts ...EvalOption) ([]byte, error)

Compile returns a compiled bytecode with given code.

func (*Context) CompileFile

func (ctx *Context) CompileFile(filePath string, opts ...EvalOption) ([]byte, error)

Compile returns a compiled bytecode with given filename.

func (*Context) CompileModule added in v0.4.14

func (ctx *Context) CompileModule(filePath string, moduleName string, opts ...EvalOption) ([]byte, error)

CompileModule returns a compiled bytecode with given code and module name.

func (*Context) Error

func (ctx *Context) Error(err error) Value

Error returns a new exception value with given message.

func (*Context) Eval

func (ctx *Context) Eval(code string, opts ...EvalOption) (Value, error)

Eval returns a js value with given code. Need call Free() `quickjs.Value`'s returned by `Eval()` and `EvalFile()` and `EvalBytecode()`. func (ctx *Context) Eval(code string) (Value, error) { return ctx.EvalFile(code, "code") }

func (*Context) EvalBytecode

func (ctx *Context) EvalBytecode(buf []byte) (Value, error)

EvalBytecode returns a js value with given bytecode. Need call Free() `quickjs.Value`'s returned by `Eval()` and `EvalFile()` and `EvalBytecode()`.

func (*Context) EvalFile

func (ctx *Context) EvalFile(filePath string, opts ...EvalOption) (Value, error)

EvalFile returns a js value with given code and filename. Need call Free() `quickjs.Value`'s returned by `Eval()` and `EvalFile()` and `EvalBytecode()`.

func (*Context) Exception

func (ctx *Context) Exception() error

Exception returns a context's exception value.

func (*Context) Float32Array added in v0.5.4

func (ctx *Context) Float32Array(data []float32) Value

Float32Array returns a Float32Array value with given float32 slice.

func (*Context) Float64

func (ctx *Context) Float64(v float64) Value

Float64 returns a float64 value with given float64.

func (*Context) Float64Array added in v0.5.4

func (ctx *Context) Float64Array(data []float64) Value

Float64Array returns a Float64Array value with given float64 slice.

func (*Context) Function

func (ctx *Context) Function(fn func(*Context, Value, []Value) Value) Value

Function returns a js function value with given function template New implementation using HandleStore and JS_NewCFunction2 with magic parameter

func (*Context) Globals

func (ctx *Context) Globals() Value

Global returns a context's global object.

func (*Context) HasException added in v0.5.3

func (ctx *Context) HasException() bool

HasException checks if the context has an exception set.

func (*Context) Int8Array added in v0.5.4

func (ctx *Context) Int8Array(data []int8) Value

Int8Array returns a Int8Array value with given int8 slice.

func (*Context) Int16Array added in v0.5.4

func (ctx *Context) Int16Array(data []int16) Value

Int16Array returns a Int16Array value with given int16 slice.

func (*Context) Int32

func (ctx *Context) Int32(v int32) Value

Int32 returns a int32 value with given int32.

func (*Context) Int32Array added in v0.5.4

func (ctx *Context) Int32Array(data []int32) Value

Int32Array returns a Int32Array value with given int32 slice.

func (*Context) Int64

func (ctx *Context) Int64(v int64) Value

Int64 returns a int64 value with given int64.

func (*Context) Invoke added in v0.1.3

func (ctx *Context) Invoke(fn Value, this Value, args ...Value) Value

Invoke invokes a function with given this value and arguments.

func (*Context) LoadModule added in v0.4.10

func (ctx *Context) LoadModule(code string, moduleName string, opts ...EvalOption) (Value, error)

LoadModule returns a js value with given code and module name.

func (*Context) LoadModuleBytecode added in v0.4.10

func (ctx *Context) LoadModuleBytecode(buf []byte, opts ...EvalOption) (Value, error)

LoadModuleByteCode returns a js value with given bytecode and module name.

func (*Context) LoadModuleFile added in v0.4.10

func (ctx *Context) LoadModuleFile(filePath string, moduleName string) (Value, error)

LoadModuleFile returns a js value with given file path and module name.

func (*Context) Loop added in v0.3.3

func (ctx *Context) Loop()

Loop runs the context's event loop.

func (*Context) Marshal added in v0.5.3

func (ctx *Context) Marshal(v interface{}) (Value, error)

Marshal returns the JavaScript value encoding of v. It traverses the value v recursively and creates corresponding JavaScript values.

Marshal uses the following type mappings:

  • bool -> JavaScript boolean
  • int, int8, int16, int32 -> JavaScript number (32-bit)
  • int64 -> JavaScript number (64-bit)
  • uint, uint8, uint16, uint32 -> JavaScript number (32-bit unsigned)
  • uint64 -> JavaScript BigInt
  • float32, float64 -> JavaScript number
  • string -> JavaScript string
  • []byte -> JavaScript ArrayBuffer
  • []int8 -> JavaScript Int8Array
  • []int16 -> JavaScript Int16Array
  • []uint16 -> JavaScript Uint16Array
  • []int32 -> JavaScript Int32Array
  • []uint32 -> JavaScript Uint32Array
  • []float32 -> JavaScript Float32Array
  • []float64 -> JavaScript Float64Array
  • []int64 -> JavaScript BigInt64Array
  • []uint64 -> JavaScript BigUint64Array
  • slice/array -> JavaScript Array
  • map -> JavaScript Object
  • struct -> JavaScript Object
  • pointer -> recursively marshal the pointed value (nil becomes null)

Struct fields are marshaled using their field names unless a tag is present. The "js" and "json" tags are supported. Fields with tag "-" are ignored.

Types implementing the Marshaler interface are marshaled using their MarshalJS method.

func (*Context) Null

func (ctx *Context) Null() Value

Null return a null value.

func (*Context) Object

func (ctx *Context) Object() Value

Object returns a new object value.

func (*Context) ParseJSON added in v0.1.11

func (ctx *Context) ParseJSON(v string) Value

ParseJson parses given json string and returns a object value.

func (*Context) Promise added in v0.5.5

func (ctx *Context) Promise(executor func(resolve, reject func(Value))) Value

Promise creates a new Promise with executor function Executor runs synchronously in current thread for thread safety

func (*Context) Runtime added in v0.4.6

func (ctx *Context) Runtime() *Runtime

Runtime returns the runtime of the context.

func (*Context) SetInterruptHandler deprecated added in v0.1.14

func (ctx *Context) SetInterruptHandler(handler InterruptHandler)

SetInterruptHandler sets a interrupt handler.

Deprecated: Use SetInterruptHandler on runtime instead

func (*Context) String

func (ctx *Context) String(v string) Value

String returns a string value with given string.

func (*Context) Throw

func (ctx *Context) Throw(v Value) Value

Throw returns a context's exception value.

func (*Context) ThrowError

func (ctx *Context) ThrowError(err error) Value

ThrowError returns a context's exception value with given error message.

func (*Context) ThrowInternalError

func (ctx *Context) ThrowInternalError(format string, args ...interface{}) Value

ThrowInternalError returns a context's exception value with given error message.

func (*Context) ThrowRangeError

func (ctx *Context) ThrowRangeError(format string, args ...interface{}) Value

ThrowRangeError returns a context's exception value with given error message.

func (*Context) ThrowReferenceError

func (ctx *Context) ThrowReferenceError(format string, args ...interface{}) Value

ThrowReferenceError returns a context's exception value with given error message.

func (*Context) ThrowSyntaxError

func (ctx *Context) ThrowSyntaxError(format string, args ...interface{}) Value

ThrowSyntaxError returns a context's exception value with given error message.

func (*Context) ThrowTypeError

func (ctx *Context) ThrowTypeError(format string, args ...interface{}) Value

ThrowTypeError returns a context's exception value with given error message.

func (*Context) Uint8Array added in v0.5.4

func (ctx *Context) Uint8Array(data []uint8) Value

Uint8Array returns a Uint8Array value with given uint8 slice.

func (*Context) Uint8ClampedArray added in v0.5.4

func (ctx *Context) Uint8ClampedArray(data []uint8) Value

Uint8ClampedArray returns a Uint8ClampedArray value with given uint8 slice.

func (*Context) Uint16Array added in v0.5.4

func (ctx *Context) Uint16Array(data []uint16) Value

Uint16Array returns a Uint16Array value with given uint16 slice.

func (*Context) Uint32

func (ctx *Context) Uint32(v uint32) Value

Uint32 returns a uint32 value with given uint32.

func (*Context) Uint32Array added in v0.5.4

func (ctx *Context) Uint32Array(data []uint32) Value

Uint32Array returns a Uint32Array value with given uint32 slice.

func (*Context) Undefined

func (ctx *Context) Undefined() Value

Undefined return a undefined value.

func (*Context) Uninitialized

func (ctx *Context) Uninitialized() Value

Uninitialized returns a uninitialized value.

func (*Context) Unmarshal added in v0.5.3

func (ctx *Context) Unmarshal(jsVal Value, v interface{}) error

Unmarshal parses the JavaScript value and stores the result in the value pointed to by v. If v is nil or not a pointer, Unmarshal returns an error.

Unmarshal uses the inverse of the encodings that Marshal uses, with the following additional rules:

  • JavaScript null/undefined -> Go nil pointer or zero value
  • JavaScript Array -> Go slice/array
  • JavaScript Object -> Go map/struct
  • JavaScript number -> Go numeric types (with appropriate conversion)
  • JavaScript BigInt -> Go uint64/int64/*big.Int
  • JavaScript ArrayBuffer -> Go []byte
  • JavaScript Int8Array -> Go []int8
  • JavaScript Int16Array -> Go []int16
  • JavaScript Uint16Array -> Go []uint16
  • JavaScript Int32Array -> Go []int32
  • JavaScript Uint32Array -> Go []uint32
  • JavaScript Float32Array -> Go []float32
  • JavaScript Float64Array -> Go []float64
  • JavaScript BigInt64Array -> Go []int64
  • JavaScript BigUint64Array -> Go []uint64

When unmarshaling into an interface{}, Unmarshal stores one of:

  • nil for JavaScript null/undefined
  • bool for JavaScript boolean
  • int64 for JavaScript integer numbers
  • float64 for JavaScript floating-point numbers
  • string for JavaScript string
  • []interface{} for JavaScript Array
  • map[string]interface{} for JavaScript Object

Types implementing the Unmarshaler interface are unmarshaled using their UnmarshalJS method.

type Error

type Error struct {
	Name       string // Error name (e.g., "TypeError", "ReferenceError")
	Message    string // Error message
	Cause      string // Error cause
	Stack      string // Stack trace
	JSONString string // Serialized JSON string
}

Error represents a JavaScript error with detailed information.

func (Error) Error

func (err Error) Error() string

Error implements the error interface.

type EvalOption added in v0.4.10

type EvalOption func(*EvalOptions)

func EvalAwait added in v0.4.10

func EvalAwait(await bool) EvalOption

func EvalFileName added in v0.4.10

func EvalFileName(filename string) EvalOption

func EvalFlagCompileOnly added in v0.4.10

func EvalFlagCompileOnly(compileOnly bool) EvalOption

func EvalFlagGlobal added in v0.4.10

func EvalFlagGlobal(global bool) EvalOption

func EvalFlagModule added in v0.4.10

func EvalFlagModule(module bool) EvalOption

func EvalFlagStrict added in v0.4.10

func EvalFlagStrict(strict bool) EvalOption

func EvalLoadOnly added in v0.5.3

func EvalLoadOnly(loadOnly bool) EvalOption

type EvalOptions added in v0.4.10

type EvalOptions struct {
	// contains filtered or unexported fields
}

type InterruptHandler added in v0.1.14

type InterruptHandler func() int

InterruptHandler is a function type for interrupt handler. Return != 0 if the JS code needs to be interrupted

type Marshaler added in v0.5.3

type Marshaler interface {
	MarshalJS(ctx *Context) (Value, error)
}

Marshaler is the interface implemented by types that can marshal themselves into a JavaScript value.

type Option added in v0.4.7

type Option func(*Options)

func WithCanBlock added in v0.4.7

func WithCanBlock(canBlock bool) Option

WithCanBlock will set the runtime's can block; default is true

func WithExecuteTimeout added in v0.4.7

func WithExecuteTimeout(timeout uint64) Option

WithExecuteTimeout will set the runtime's execute timeout; default is 0

func WithGCThreshold added in v0.4.7

func WithGCThreshold(gcThreshold int64) Option

WithGCThreshold will set the runtime's GC threshold; default is -1 to disable automatic GC.

func WithMaxStackSize added in v0.4.7

func WithMaxStackSize(maxStackSize uint64) Option

WithMaxStackSize will set max runtime's stack size; default is 0 disable maximum stack size check

func WithMemoryLimit added in v0.4.7

func WithMemoryLimit(memoryLimit uint64) Option

WithMemoryLimit will set the runtime memory limit; if not set, it will be unlimit.

func WithModuleImport added in v0.4.10

func WithModuleImport(moduleImport bool) Option

func WithStripInfo added in v0.5.0

func WithStripInfo(strip int) Option

type Options added in v0.4.7

type Options struct {
	// contains filtered or unexported fields
}

type PromiseState added in v0.5.5

type PromiseState int

Promise state enumeration matching QuickJS

const (
	PromisePending PromiseState = iota
	PromiseFulfilled
	PromiseRejected
)

type Runtime

type Runtime struct {
	// contains filtered or unexported fields
}

Runtime represents a Javascript runtime with simplified interrupt handling

func NewRuntime

func NewRuntime(opts ...Option) *Runtime

NewRuntime creates a new quickjs runtime with simplified interrupt handling.

func (*Runtime) ClearInterruptHandler added in v0.5.5

func (r *Runtime) ClearInterruptHandler()

ClearInterruptHandler clears the user interrupt handler

func (*Runtime) Close

func (r *Runtime) Close()

Close will free the runtime pointer with proper cleanup.

func (*Runtime) NewContext

func (r *Runtime) NewContext() *Context

NewContext creates a new JavaScript context.

func (*Runtime) RunGC

func (r *Runtime) RunGC()

RunGC will call quickjs's garbage collector.

func (*Runtime) SetCanBlock added in v0.4.7

func (r *Runtime) SetCanBlock(canBlock bool)

SetCanBlock will set the runtime's can block; default is true

func (*Runtime) SetExecuteTimeout added in v0.4.7

func (r *Runtime) SetExecuteTimeout(timeout uint64)

SetExecuteTimeout will set the runtime's execute timeout; This will override any user interrupt handler (expected behavior)

func (*Runtime) SetGCThreshold

func (r *Runtime) SetGCThreshold(threshold int64)

SetGCThreshold the runtime's GC threshold; use -1 to disable automatic GC.

func (*Runtime) SetInterruptHandler added in v0.5.0

func (r *Runtime) SetInterruptHandler(handler InterruptHandler)

SetInterruptHandler sets a user interrupt handler using simplified approach. This will override any timeout handler (expected behavior)

func (*Runtime) SetMaxStackSize

func (r *Runtime) SetMaxStackSize(stack_size uint64)

SetMaxStackSize will set max runtime's stack size;

func (*Runtime) SetMemoryLimit

func (r *Runtime) SetMemoryLimit(limit uint64)

SetMemoryLimit the runtime memory limit; if not set, it will be unlimit.

func (*Runtime) SetStripInfo added in v0.5.0

func (r *Runtime) SetStripInfo(strip int)

type Unmarshaler added in v0.5.3

type Unmarshaler interface {
	UnmarshalJS(ctx *Context, val Value) error
}

Unmarshaler is the interface implemented by types that can unmarshal a JavaScript value into themselves.

type Value

type Value struct {
	// contains filtered or unexported fields
}

JSValue represents a Javascript value which can be a primitive type or an object. Reference counting is used, so it is important to explicitly duplicate (JS_DupValue(), increment the reference count) or free (JS_FreeValue(), decrement the reference count) JSValues.

func (Value) Await added in v0.5.5

func (v Value) Await() (Value, error)

Await waits for promise resolution and executes pending jobs Similar to Context.Await but called on Value directly

func (Value) BigInt deprecated

func (v Value) BigInt() *big.Int

Deprecated: Use ToBigInt instead.

func (Value) Bool deprecated

func (v Value) Bool() bool

Deprecated: Use ToBool instead.

func (Value) ByteLen added in v0.1.13

func (v Value) ByteLen() int64

ByteLen returns the length of the ArrayBuffer.

func (Value) Call

func (v Value) Call(fname string, args ...Value) Value

Call calls the function with the given arguments.

func (Value) CallConstructor added in v0.4.15

func (v Value) CallConstructor(args ...Value) Value

Call calls the constructor with the given arguments.

func (Value) Context

func (v Value) Context() *Context

Context represents a Javascript context.

func (Value) Delete

func (v Value) Delete(name string) bool

Delete deletes the property with the given name.

func (Value) DeleteIdx

func (v Value) DeleteIdx(idx uint32) bool

DeleteIdx deletes the property with the given index.

func (Value) Error deprecated

func (v Value) Error() error

Deprecated: Use ToError() instead.

func (Value) Execute added in v0.5.0

func (v Value) Execute(this Value, args ...Value) Value

Execute the function with the given arguments.

func (Value) Float64 deprecated

func (v Value) Float64() float64

Deprecated: Use ToFloat64 instead.

func (Value) Free

func (v Value) Free()

Free the value.

func (Value) Get

func (v Value) Get(name string) Value

Get returns the value of the property with the given name.

func (Value) GetIdx

func (v Value) GetIdx(idx int64) Value

GetIdx returns the value of the property with the given index.

func (Value) GlobalInstanceof added in v0.5.0

func (v Value) GlobalInstanceof(name string) bool

GlobalInstanceof checks if the value is an instance of the given global constructor

func (Value) Has

func (v Value) Has(name string) bool

Has returns true if the value has the property with the given name.

func (Value) HasIdx

func (v Value) HasIdx(idx uint32) bool

HasIdx returns true if the value has the property with the given index.

func (Value) Int32 deprecated

func (v Value) Int32() int32

Deprecated: Use ToInt32 instead.

func (Value) Int64 deprecated

func (v Value) Int64() int64

Deprecated: Use ToInt64 instead.

func (Value) IsArray

func (v Value) IsArray() bool

func (Value) IsBigInt

func (v Value) IsBigInt() bool

func (Value) IsBigInt64Array added in v0.5.4

func (v Value) IsBigInt64Array() bool

func (Value) IsBigUint64Array added in v0.5.4

func (v Value) IsBigUint64Array() bool

func (Value) IsBool

func (v Value) IsBool() bool

func (Value) IsByteArray added in v0.1.13

func (v Value) IsByteArray() bool

IsByteArray return true if the value is array buffer

func (Value) IsConstructor added in v0.4.15

func (v Value) IsConstructor() bool

func (Value) IsError

func (v Value) IsError() bool

func (Value) IsException

func (v Value) IsException() bool

func (Value) IsFloat32Array added in v0.5.4

func (v Value) IsFloat32Array() bool

func (Value) IsFloat64Array added in v0.5.4

func (v Value) IsFloat64Array() bool

func (Value) IsFunction

func (v Value) IsFunction() bool

func (Value) IsInt8Array added in v0.5.4

func (v Value) IsInt8Array() bool

func (Value) IsInt16Array added in v0.5.4

func (v Value) IsInt16Array() bool

func (Value) IsInt32Array added in v0.5.4

func (v Value) IsInt32Array() bool

func (Value) IsNull

func (v Value) IsNull() bool

func (Value) IsNumber

func (v Value) IsNumber() bool

func (Value) IsObject

func (v Value) IsObject() bool

func (Value) IsPromise added in v0.4.9

func (v Value) IsPromise() bool

func (Value) IsString

func (v Value) IsString() bool

func (Value) IsSymbol

func (v Value) IsSymbol() bool

func (Value) IsTypedArray added in v0.5.4

func (v Value) IsTypedArray() bool

TypedArray detection methods

func (Value) IsUint8Array added in v0.5.4

func (v Value) IsUint8Array() bool

func (Value) IsUint8ClampedArray added in v0.5.4

func (v Value) IsUint8ClampedArray() bool

func (Value) IsUint16Array added in v0.5.4

func (v Value) IsUint16Array() bool

func (Value) IsUint32Array added in v0.5.4

func (v Value) IsUint32Array() bool

func (Value) IsUndefined

func (v Value) IsUndefined() bool

func (Value) IsUninitialized

func (v Value) IsUninitialized() bool

func (Value) JSONStringify added in v0.1.11

func (v Value) JSONStringify() string

JSONStringify returns the JSON string representation of the value.

func (Value) Len

func (v Value) Len() int64

Len returns the length of the array.

func (Value) New added in v0.4.15

func (v Value) New(args ...Value) Value

Call Class Constructor

func (Value) PromiseState added in v0.5.5

func (v Value) PromiseState() PromiseState

PromiseState returns the state of the Promise

func (Value) PropertyNames

func (v Value) PropertyNames() ([]string, error)

PropertyNames returns the names of the properties of the value.

func (Value) Set

func (v Value) Set(name string, val Value)

Set sets the value of the property with the given name.

func (Value) SetIdx

func (v Value) SetIdx(idx int64, val Value)

SetIdx sets the value of the property with the given index.

func (Value) String

func (v Value) String() string

String returns the string representation of the value. This method implements the fmt.Stringer interface.

func (Value) ToBigInt added in v0.5.0

func (v Value) ToBigInt() *big.Int

ToBigInt returns the big.Int value of the value.

func (Value) ToBigInt64Array added in v0.5.4

func (v Value) ToBigInt64Array() ([]int64, error)

ToBigInt64Array converts the value to int64 slice if it's a BigInt64Array.

func (Value) ToBigUint64Array added in v0.5.4

func (v Value) ToBigUint64Array() ([]uint64, error)

ToBigUint64Array converts the value to uint64 slice if it's a BigUint64Array.

func (Value) ToBool added in v0.5.0

func (v Value) ToBool() bool

ToBool returns the boolean value of the value.

func (Value) ToByteArray added in v0.1.13

func (v Value) ToByteArray(size uint) ([]byte, error)

func (Value) ToError added in v0.5.0

func (v Value) ToError() error

ToError returns the error value of the value.

func (Value) ToFloat32Array added in v0.5.4

func (v Value) ToFloat32Array() ([]float32, error)

ToFloat32Array converts the value to float32 slice if it's a Float32Array.

func (Value) ToFloat64 added in v0.5.0

func (v Value) ToFloat64() float64

ToFloat64 returns the float64 value of the value.

func (Value) ToFloat64Array added in v0.5.4

func (v Value) ToFloat64Array() ([]float64, error)

ToFloat64Array converts the value to float64 slice if it's a Float64Array.

func (Value) ToInt8Array added in v0.5.4

func (v Value) ToInt8Array() ([]int8, error)

ToInt8Array converts the value to int8 slice if it's an Int8Array.

func (Value) ToInt16Array added in v0.5.4

func (v Value) ToInt16Array() ([]int16, error)

ToInt16Array converts the value to int16 slice if it's an Int16Array.

func (Value) ToInt32 added in v0.5.0

func (v Value) ToInt32() int32

ToInt32 returns the int32 value of the value.

func (Value) ToInt32Array added in v0.5.4

func (v Value) ToInt32Array() ([]int32, error)

ToInt32Array converts the value to int32 slice if it's an Int32Array.

func (Value) ToInt64 added in v0.5.0

func (v Value) ToInt64() int64

ToInt64 returns the int64 value of the value.

func (Value) ToString added in v0.5.0

func (v Value) ToString() string

ToString returns the string representation of the value.

func (Value) ToUint8Array added in v0.5.4

func (v Value) ToUint8Array() ([]uint8, error)

ToUint8Array converts the value to uint8 slice if it's a Uint8Array or Uint8ClampedArray.

func (Value) ToUint16Array added in v0.5.4

func (v Value) ToUint16Array() ([]uint16, error)

ToUint16Array converts the value to uint16 slice if it's a Uint16Array.

func (Value) ToUint32 added in v0.5.0

func (v Value) ToUint32() uint32

ToUint32 returns the uint32 value of the value.

func (Value) ToUint32Array added in v0.5.4

func (v Value) ToUint32Array() ([]uint32, error)

ToUint32Array converts the value to uint32 slice if it's a Uint32Array.

func (Value) Uint32 deprecated

func (v Value) Uint32() uint32

Deprecated: Use ToUint32 instead.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL