napi

package module
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: May 17, 2025 License: MIT Imports: 12 Imported by: 0

README

napi-go

A Go library for building Node.js Native Addons using Node-API.

[!IMPORTANT]

This module require CGO, to cross-compile check cgo documentation.

My recommendation is to use a Linux distribution with the GCC installed together with the Required Destinations, or use zig(C: zig cc -target <target>, C++: zig c++ -target <target>)

Usage

Get module with go get -u sirherobrine23.com.br/Sirherobrine23/napi-go@latest

register function to export values on module start, example

package main

import (
	"encoding/json"
	"net/netip"
	_ "unsafe"

	"sirherobrine23.com.br/Sirherobrine23/napi-go"
	_ "sirherobrine23.com.br/Sirherobrine23/napi-go/module"
	"sirherobrine23.com.br/Sirherobrine23/napi-go/js"
)

type Test struct {
	Int    int
	String string
	Sub    []any
}

//go:linkname RegisterNapi sirherobrine23.com.br/Sirherobrine23/napi-go/entry.Register
func RegisterNapi(env napi.EnvType, export *napi.Object) {
	inNode, _ := napi.CreateString(env, "from golang napi string")
	inNode2, _ := napi.CopyBuffer(env, []byte{1, 0, 244, 21})
	toGoReflect := &Test{
		Int:    14,
		String: "From golang",
		Sub: []any{
			1,
			[]string{"test", "gopher"},
			[]bool{false, true},
			[]int{23, 244, 10, 2024, 2025, 2000},
			map[string]string{"exampleMap": "test"},
			map[int]string{1: "one"},
			map[bool]string{false: "false", true: "true"},
			map[[2]string]string{{"go"}: "example"},
			netip.IPv4Unspecified(),
			netip.IPv6Unspecified(),
			netip.AddrPortFrom(netip.IPv6Unspecified(), 19132),
			nil,
			true,
			false,
			inNode,
			inNode2,
			func() {
				println("called in go")
			},
		},
	}

	napiStruct, err := js.ValueOf(env, toGoReflect)
	if err != nil {
		panic(err)
	}
	export.Set("goStruct", napiStruct)

	fnCall, err := js.GoFuncOf(env, func(call ...any) (string, error) {
		d, err := json.MarshalIndent(call, "", "  ")
		if err == nil {
			println(string(d))
		}
		return string(d), err
	})
	if err != nil {
		panic(err)
	}
	export.Set("printAny", fnCall)

	fnCallStruct, err := js.GoFuncOf(env, func(call ...Test) (string, error) {
		d, err := json.MarshalIndent(call, "", "  ")
		if err == nil {
			println(string(d))
		}
		return string(d), err
	})
	if err != nil {
		panic(err)
	}
	export.Set("printTestStruct", fnCallStruct)
}

func main() {}

Finally, build the Node.js addon using go build:

go build -buildmode=c-shared -o "example.node" .

se more examples in internal/examples

Go bind

Now there are some new functions that convert values ​​from Golang to JavaScript and Versa-Versa.

They are the:

  • ValueOf: Convert go values to Javascript values.
  • ValueFrom Convert Javascript values to Golang values.
From Go to Javascript:
  • Function
  • Struct, Map
  • Slice and Array
  • String
  • Int*, Uint* and Float
  • Boolean
  • Interface (interface if is any and not nil)
  • Promise
    • Async Worker
    • Thread safe function
  • Array buffer
  • Dataview
  • Typed Array
  • Class
Convert from Javascript values to Go
  • Struct, Map
  • Slice and Array
  • String
  • Int*, Uint* and Float
  • Boolean
  • Interface (if is any set types map[string]any, []any or primitive values)
  • Array buffer
  • Typed Array
  • Dataview
  • Function
  • Class

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func As added in v0.1.2

func As[T ValueType](input ValueType) T

Casts to another type of ValueType, when the actual type is known or assumed.

This conversion does NOT coerce the type. Calling any methods inappropriate for the actual value type.

func StrictEqual added in v0.1.2

func StrictEqual(env EnvType, lhs, rhs ValueType) (bool, error)

This API represents the invocation of the Strict Equality algorithm as defined in https://tc39.github.io/ecma262/#sec-strict-equality-comparison of the ECMAScript Language Specification.

func ThrowError

func ThrowError(env EnvType, code, err string) error

ThrowError throws a JavaScript error in the given N-API environment with the specified code and error message. If the code is an empty string, it captures the current Go stack trace and uses it as the error code. Returns an error if the underlying N-API call fails.

Parameters:

  • env: The N-API environment in which to throw the error.
  • code: The error code to associate with the thrown error. If empty, the current stack trace is used.
  • err: The error message to be thrown.

func ValueFrom added in v0.1.2

func ValueFrom(napiValue ValueType, v any) error

ValueFrom converts a N-API value (napiValue) to a Go value and stores the result in v. The v parameter must be a pointer to the target Go variable where the converted value will be stored. Returns an error if v is not a pointer or if the conversion fails.

Types

type Array

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

func CreateArray

func CreateArray(env EnvType, size ...int) (*Array, error)

Create Array.

func ToArray

func ToArray(o ValueType) *Array

Convert ValueType to *Array.

func (*Array) Append

func (arr *Array) Append(values ...ValueType) error

Append adds one or more values to the end of the array. It accepts a variadic number of ValueType arguments and appends each to the array, starting from the current length. If an error occurs during the append operation, it returns the error; otherwise, it returns nil.

func (*Array) Delete

func (arr *Array) Delete(index int) (bool, error)

Delete index elemente from array.

func (*Array) From added in v0.1.2

func (arr *Array) From(from iter.Seq[any]) (err error)

Populates the Array with elements from the provided iterator sequence. For each element in the sequence, it converts the value to ValueType if necessary, and appends it to the end of the Array. If an error occurs during conversion or insertion, the operation stops and the error is returned. Returns error if an error if any occurs during value conversion or insertion; otherwise, nil.

func (*Array) Get

func (arr *Array) Get(index int) (ValueType, error)

Get Value from index

func (*Array) Length

func (arr *Array) Length() (int, error)

Get array length.

func (*Array) Seq

func (arr *Array) Seq() iter.Seq[ValueType]

Get values with iter.Seq

func (*Array) Set

func (arr *Array) Set(index int, value ValueType) error

Set value in index

type ArrayBuffer added in v0.1.2

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

ArrayBuffer represents a JavaScript ArrayBuffer.

func CreateArrayBuffer added in v0.1.2

func CreateArrayBuffer(env EnvType, length int) (*ArrayBuffer, []byte, error)

CreateArrayBuffer creates a new JavaScript ArrayBuffer instance. It also returns a pointer to the underlying byte buffer.

func CreateExternalArrayBuffer added in v0.1.2

func CreateExternalArrayBuffer(env EnvType, data []byte, finalize napi.Finalize, finalizeHint unsafe.Pointer) (*ArrayBuffer, error)

CreateExternalArrayBuffer creates a JavaScript ArrayBuffer instance over an existing external data buffer. The caller is responsible for managing the lifetime of the data buffer. The finalize callback will be invoked when the ArrayBuffer is garbage collected.

func ToArrayBuffer added in v0.1.2

func ToArrayBuffer(o ValueType) *ArrayBuffer

ToArrayBuffer converts a ValueType to *ArrayBuffer. It assumes the underlying N-API value is an ArrayBuffer. Use IsArrayBuffer to check before converting.

func (*ArrayBuffer) ByteLength added in v0.1.2

func (ab *ArrayBuffer) ByteLength() (int, error)

ByteLength retrieves the length (in bytes) of the ArrayBuffer. This is a convenience wrapper around Info().

func (*ArrayBuffer) Data added in v0.1.2

func (ab *ArrayBuffer) Data() ([]byte, error)

Data retrieves the underlying byte data of the ArrayBuffer as a Go slice. This is a convenience wrapper around Info().

func (*ArrayBuffer) Detach added in v0.1.2

func (ab *ArrayBuffer) Detach() error

Detach detaches the ArrayBuffer, making its contents inaccessible from JavaScript. This is used for transferring ownership of the underlying buffer.

func (*ArrayBuffer) Info added in v0.1.2

func (ab *ArrayBuffer) Info() ([]byte, int, error)

Info retrieves information about the ArrayBuffer, including its underlying data buffer and length.

func (*ArrayBuffer) IsDetached added in v0.1.2

func (ab *ArrayBuffer) IsDetached() (bool, error)

IsDetached checks if the ArrayBuffer has been detached.

type AsyncWorker added in v0.1.1

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

AsyncWorker encapsulates an asynchronous worker for executing tasks in a separate thread using Node.js N-API. It embeds a value type and manages the lifecycle of an async work operation, including its associated promise for JavaScript interoperability.

func CreateAsyncWorker added in v0.1.2

func CreateAsyncWorker(env EnvType, exec CallbackAsyncWorkerExec, done CallbackAsyncWorkerDone) (*AsyncWorker, error)

CreateAsyncWorker creates an asynchronous worker that executes the provided exec function in a separate thread, and calls the done callback upon completion. It returns an AsyncWorker instance and a promise that can be used to track the asynchronous operation from JavaScript.

The promise is resolved or rejected based on the outcome of the async operation. If an error or panic occurs during execution, the promise is rejected with the corresponding error. If the async worker is cancelled, the promise is also rejected.

func (*AsyncWorker) Cancel added in v0.1.1

func (async *AsyncWorker) Cancel() error

Cancel attempts to cancel the asynchronous work associated with the AsyncWorker. It returns an error if the cancellation fails or if the async work cannot be cancelled.

type Bigint

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

func CreateBigint

func CreateBigint[T int64 | uint64](env EnvType, valueOf T) (*Bigint, error)

CreateBigint creates a new Bigint value in the given N-API environment from the provided int64 or uint64 value. The function is generic and accepts either int64 or uint64 as the input type. It returns a pointer to a Bigint and an error if the creation fails.

func ToBigint

func ToBigint(o ValueType) *Bigint

Convert ValueType to *Bigint

func (*Bigint) Int64

func (big *Bigint) Int64() (int64, error)

Int64 returns the value of the Bigint as an int64 along with an error if the conversion fails. It retrieves the int64 representation of the underlying N-API BigInt value. If the value cannot be represented as an int64, an error is returned.

func (*Bigint) Uint64

func (big *Bigint) Uint64() (uint64, error)

Uint64 returns the value of the Bigint as a uint64 along with an error if the conversion fails. It retrieves the underlying BigInt value from the N-API environment and attempts to convert it to a uint64. If the value cannot be represented as a uint64 or if an error occurs during retrieval, an error is returned.

type Boolean

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

func CreateBoolean

func CreateBoolean(env EnvType, value bool) (*Boolean, error)

CreateBoolean creates a new Boolean value in the given N-API environment. It takes an EnvType representing the N-API environment and a Go bool value. Returns a pointer to a Boolean object representing the value in the N-API environment, or an error if the creation fails.

func ToBoolean

func ToBoolean(o ValueType) *Boolean

Convert ValueType to *Boolean

func (*Boolean) Value

func (bo *Boolean) Value() (bool, error)

Value retrieves the boolean value represented by the Boolean object. It returns the Go bool value and an error if the underlying N-API call fails.

type Buffer

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

func CopyBuffer

func CopyBuffer(env EnvType, buff []byte) (*Buffer, error)

Copy []byte to Node::Buffer struct

func CreateBuffer

func CreateBuffer(env EnvType, length int) (*Buffer, error)

Create new Buffer with length

func ToBuffer

func ToBuffer(o ValueType) *Buffer

Convert ValueType to *Buffer.

func (*Buffer) Data

func (buff *Buffer) Data() ([]byte, error)

return []byte from Buffer value

func (*Buffer) Length

func (buff *Buffer) Length() (int, error)

Get size of buffer

type Callback

type Callback func(env EnvType, this ValueType, args []ValueType) (ValueType, error)

Function to call on Javascript caller

type CallbackAsyncWorkerDone added in v0.1.2

type CallbackAsyncWorkerDone func(env EnvType, Resolve, Reject func(value ValueType))

Funtion to run after exec code

type CallbackAsyncWorkerExec added in v0.1.2

type CallbackAsyncWorkerExec func(env EnvType)

function to run code in background without locker Loop event

type DataView added in v0.1.2

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

DataView represents a JavaScript DataView object.

func CreateDataView added in v0.1.2

func CreateDataView(env EnvType, buffer *ArrayBuffer, byteOffset, byteLength int) (*DataView, error)

CreateDataView creates a new JavaScript DataView instance over an existing ArrayBuffer.

func ToDataView added in v0.1.2

func ToDataView(o ValueType) *DataView

ToDataView converts a ValueType to *DataView. It assumes the underlying N-API value is a DataView. Use IsDataView to check before converting.

func (*DataView) Buffer added in v0.1.2

func (dv *DataView) Buffer() (*ArrayBuffer, error)

Buffer returns the underlying ArrayBuffer referenced by the DataView. This is a convenience wrapper around Info().

func (*DataView) ByteLength added in v0.1.2

func (dv *DataView) ByteLength() (int, error)

ByteLength returns the length (in bytes) of the DataView. This is a convenience wrapper around Info().

func (*DataView) ByteOffset added in v0.1.2

func (dv *DataView) ByteOffset() (int, error)

ByteOffset returns the offset (in bytes) of the DataView within its underlying ArrayBuffer. This is a convenience wrapper around Info().

func (*DataView) Info added in v0.1.2

func (dv *DataView) Info() (buffer *ArrayBuffer, byteLength int, byteOffset int, dataPtr unsafe.Pointer, err error)

Info retrieves information about the DataView, including the underlying ArrayBuffer, its byte length, and the byte offset within the buffer. It also returns a pointer to the start of the DataView's section within the buffer's data.

type Date

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

func CreateDate

func CreateDate(env EnvType, t time.Time) (*Date, error)

CreateDate creates a new JavaScript Date object in the given N-API environment using the provided Go time.Time value. It returns a pointer to a Date wrapper or an error if the creation fails.

func ToDate

func ToDate(o ValueType) *Date

Convert ValueType to *Date

func (Date) Time

func (d Date) Time() (time.Time, error)

Time returns the Go time.Time representation of the Date value. It retrieves the date value from the underlying N-API environment, converts it to a Unix millisecond timestamp, and constructs a time.Time object. If an error occurs during value retrieval or conversion, it is returned.

type EnvType

type EnvType interface {
	NapiValue() napi.Env // Primitive value to NAPI call
	Global() (*Object, error)
	Undefined() (ValueType, error)
	Null() (ValueType, error)
}

EnvType defines an interface for interacting with a NAPI environment. It provides methods to retrieve the underlying NAPI environment, access the global object, and obtain the JavaScript 'undefined' and 'null' values as Go types.

func N_APIEnv

func N_APIEnv(env napi.Env) EnvType

Return N-API env reference

type Error

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

func CreateError

func CreateError(env EnvType, msg string) (*Error, error)

CreateError creates a new JavaScript Error object in the given N-API environment with the specified message. It returns a pointer to the Error object and an error if the creation fails at any step.

func ToError

func ToError(o ValueType) *Error

func (*Error) ThrowAsJavaScriptException

func (er *Error) ThrowAsJavaScriptException() error

ThrowAsJavaScriptException throws the current Error as a JavaScript exception in the associated N-API environment. It returns an error if the operation fails.

type External added in v0.1.2

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

func CreateExternal added in v0.1.2

func CreateExternal(env EnvType, data unsafe.Pointer, finalize napi.Finalize, finalizeHint unsafe.Pointer) (*External, error)

CreateExternal creates a new JavaScript external value in the given N-API environment. It associates the provided data pointer with the external, and allows specifying a finalize callback and a finalize hint, which will be called when the external is garbage collected.

func ToExternal added in v0.1.2

func ToExternal(o ValueType) *External

func (*External) Value added in v0.1.2

func (ext *External) Value() (unsafe.Pointer, error)

Value retrieves the underlying unsafe.Pointer associated with the External value. Returns the pointer and an error, if any occurred during retrieval.

type Function

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

func CreateFunction

func CreateFunction(env EnvType, name string, callback Callback) (*Function, error)

func CreateFunctionNapi

func CreateFunctionNapi(env EnvType, name string, callback napi.Callback) (*Function, error)

Create function from internal napi.Callback

func ToFunction

func ToFunction(o ValueType) *Function

Convert ValueType to *Function

func (*Function) Call

func (fn *Function) Call(args ...ValueType) (ValueType, error)

Call function with args

func (*Function) CallWithGlobal

func (fn *Function) CallWithGlobal(this ValueType, args ...ValueType) (ValueType, error)

Call function with custom global/this value

type NapiType

type NapiType int

Typeof of Value

const (
	TypeUnkown NapiType = iota
	TypeUndefined
	TypeNull
	TypeBoolean
	TypeNumber
	TypeBigInt
	TypeString
	TypeSymbol
	TypeObject
	TypeFunction
	TypeExternal
	TypeTypedArray
	TypePromise
	TypeDataView
	TypeBuffer
	TypeDate
	TypeArray
	TypeArrayBuffer
	TypeError
)

napi-go stand types

func (NapiType) String

func (t NapiType) String() string

String returns the string representation of the NapiType. If the NapiType is known, it returns its name; otherwise, it returns a formatted string indicating an unknown type.

type NodeVersion added in v0.1.2

type NodeVersion = napi.NodeVersion

func GetNodeVersion added in v0.1.2

func GetNodeVersion(env EnvType) (*NodeVersion, error)

GetNodeVersion retrieves the Node.js version information for the given environment. It takes an EnvType as input and returns a pointer to a NodeVersion struct and an error. If the version retrieval fails, it returns a non-nil error.

type Number

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

func CreateNumber

func CreateNumber[T ~int | ~uint | ~int8 | ~uint8 | ~int16 | ~uint16 | ~int32 | ~uint32 | ~int64 | ~uint64 | ~float32 | ~float64](env EnvType, n T) (*Number, error)

CreateNumber creates a new JavaScript Number object from a Go numeric value of type T. The function supports various integer and floating-point types, including int, uint, int8, uint8, int16, uint16, int32, uint32, int64, uint64, float32, and float64. It converts the provided Go value to the appropriate JavaScript number representation using the N-API environment.

func ToNumber

func ToNumber(o ValueType) *Number

Convert ValueType to *Number

func (*Number) Float

func (num *Number) Float() (float64, error)

Float returns the float64 representation of the Number. It retrieves the underlying value from the N-API environment and value handle. If the conversion fails, an error is returned.

func (*Number) Int

func (num *Number) Int() (int64, error)

Int returns the int64 representation of the Number. It calls napi.GetValueInt64 using the underlying NapiEnv and NapiValue. If the conversion fails, an error is returned.

func (*Number) Int32

func (num *Number) Int32() (int32, error)

Int32 retrieves the value of the Number as an int32. It returns the int32 representation of the Number and an error if the conversion fails.

func (*Number) Uint32

func (num *Number) Uint32() (uint32, error)

Uint32 retrieves the value of the Number as a uint32. It returns the uint32 representation of the Number and an error if the conversion fails.

type Object

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

func CreateObject

func CreateObject(env EnvType) (*Object, error)

Create *Object

func ToObject

func ToObject(o ValueType) *Object

Convert ValueType to *Object

func (*Object) Delete

func (obj *Object) Delete(key string) (bool, error)

Delete property.

func (*Object) DeleteWithValue

func (obj *Object) DeleteWithValue(key ValueType) (bool, error)

Delete property.

func (*Object) Freeze

func (obj *Object) Freeze() error

This method freezes a given object.

This prevents new properties from being added to it, existing properties from being removed, prevents changing the enumerability, configurability, or writability of existing properties, and prevents the values of existing properties from being changed.

It also prevents the object's prototype from being changed.

func (*Object) From added in v0.1.2

func (obj *Object) From(from iter.Seq2[any, any]) (err error)

Copy from iter to Object

func (*Object) Get

func (obj *Object) Get(key string) (ValueType, error)

Gets a property.

func (*Object) GetPropertyNames

func (obj *Object) GetPropertyNames() (*Array, error)

Get all property names.

func (*Object) GetWithValue

func (obj *Object) GetWithValue(key ValueType) (ValueType, error)

Gets a property.

func (*Object) Has

func (obj *Object) Has(name string) (bool, error)

Check if exists named property.

func (*Object) HasOwnProperty

func (obj *Object) HasOwnProperty(key ValueType) (bool, error)

Checks whether a own property is present.

func (*Object) HasOwnPropertyString

func (obj *Object) HasOwnPropertyString(keyString string) (bool, error)

Checks whether a own property is present.

func (*Object) InstanceOf

func (obj *Object) InstanceOf(value ValueType) (bool, error)

Checks if an object is an instance created by a constructor function, this is equivalent to the JavaScript `instanceof` operator.

func (*Object) Seal

func (obj *Object) Seal() error

This method seals a given object.

This prevents new properties from being added to it, as well as marking all existing properties as non-configurable.

func (*Object) Seq

func (obj *Object) Seq() iter.Seq2[string, ValueType]

Seq returns an iterator (Seq2) over the object's property names and their corresponding values. It retrieves all property names of the object, and for each property, yields the property's name as a string and its associated ValueType. If an error occurs while retrieving property names or values, the function panics. The iteration stops if the yield function returns false.

func (*Object) Set

func (obj *Object) Set(key string, value ValueType) error

Sets a property.

func (*Object) SetWithValue

func (obj *Object) SetWithValue(key, value ValueType) error

Sets a property.

type Promise added in v0.1.1

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

func CreatePromise added in v0.1.1

func CreatePromise(env EnvType) (*Promise, error)

CreatePromise creates a new JavaScript Promise object in the given N-API environment. It returns a pointer to the created Promise and an error if the operation fails. The function internally calls napi.CreatePromise to obtain the promise value and deferred handle. If an error occurs during promise creation, it is converted and returned.

func ToPromise added in v0.1.1

func ToPromise(o ValueType) *Promise

If ValueType is *Promise return else panic

func (*Promise) Reject added in v0.1.1

func (promise *Promise) Reject(value ValueType) error

Reject rejects the promise with the provided value. It calls napi.RejectDeferred to reject the underlying N-API deferred promise using the given ValueType. Returns an error if the rejection fails.

func (*Promise) Resolve added in v0.1.1

func (promise *Promise) Resolve(value ValueType) error

Resolve fulfills the promise with the provided value. It resolves the underlying N-API deferred object using the given ValueType. Returns an error if the resolution fails.

type String

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

func CreateString

func CreateString(env EnvType, str string) (*String, error)

Create *String from go string

func CreateStringUtf16

func CreateStringUtf16(env EnvType, str []rune) (*String, error)

Create string to utf16

func ToString

func ToString(o ValueType) *String

Convert ValueType to *String

func (*String) Utf8Value

func (str *String) Utf8Value() (string, error)

Get String value.

func (*String) Utf16Value

func (str *String) Utf16Value() ([]rune, error)

Converts a String value to a UTF-16 encoded in rune.

type TypedArray added in v0.1.2

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

func CreateTypedArray added in v0.1.2

func CreateTypedArray(env EnvType, Type TypedArrayType, length, byteOffset int, arrayValue *ArrayBuffer) (*TypedArray, error)

CreateTypedArray creates a new typed array of the specified type and length, backed by the provided ArrayBuffer. The function takes the environment (env), the typed array type (Type), the desired length, the byte offset within the buffer, and a pointer to the ArrayBuffer. It returns a pointer to the created TypedArray of type T, or an error if the operation fails.

Parameters:

  • env: The environment in which to create the typed array.
  • Type: The type of the typed array to create (e.g., Int8Array, Float32Array).
  • length: The number of elements in the typed array.
  • byteOffset: The offset in bytes from the start of the ArrayBuffer.
  • arrayValue: Pointer to the ArrayBuffer to use as the backing store.

func ToTypedArray added in v0.1.2

func ToTypedArray(value ValueType) *TypedArray

Return Generic Value to TypedArray

func (TypedArray) Get added in v0.1.2

func (typed TypedArray) Get() (data []byte, arr *ArrayBuffer, err error)

Get retrieves the underlying byte slice and associated ArrayBuffer from the TypedArray. It returns the data as a byte slice, a pointer to the ArrayBuffer, and an error if the operation fails. The function extracts the necessary information using napi.GetTypedArrayInfo and handles any status errors accordingly.

func (TypedArray) Type added in v0.1.2

func (typed TypedArray) Type() TypedArrayType

Type returns the type of the TypedArray as a TypedArrayType. This method is used to retrieve the specific type of the TypedArray instance. It returns the type as a TypedArrayType constant, which can be used to identify the kind of typed array (e.g., Int8Array, Float32Array, etc.). The function is a method of the TypedArray struct and does not take any parameters. It is a simple getter method that returns the type of the TypedArray.

type TypedArrayType added in v0.1.2

type TypedArrayType = napi.TypedArrayType
const (
	TypedArrayInt8Array         TypedArrayType = napi.TypedArrayInt8Array
	TypedArrayUint8Array        TypedArrayType = napi.TypedArrayUint8Array
	TypedArrayUint8ClampedArray TypedArrayType = napi.TypedArrayUint8ClampedArray
	TypedArrayInt16Array        TypedArrayType = napi.TypedArrayInt16Array
	TypedArrayUint16Array       TypedArrayType = napi.TypedArrayUint16Array
	TypedArrayInt32Array        TypedArrayType = napi.TypedArrayInt32Array
	TypedArrayUint32Array       TypedArrayType = napi.TypedArrayUint32Array
	TypedArrayFloat32Array      TypedArrayType = napi.TypedArrayFloat32Array
	TypedArrayFloat64Array      TypedArrayType = napi.TypedArrayFloat64Array
	TypedArrayBigInt64Array     TypedArrayType = napi.TypedArrayBigInt64Array
	TypedArrayBigUint64Array    TypedArrayType = napi.TypedArrayBigUint64Array
)

type ValueType

type ValueType interface {
	Env() EnvType            // NAPI Env to NAPI call
	Type() (NapiType, error) // NAPI Type of value
	NapiValue() napi.Value   // Primitive value to NAPI call
	NapiEnv() napi.Env       // NAPI Env to NAPI call
}

ValueType defines an interface for types that can be represented as N-API values. It provides methods to retrieve the underlying napi.Value and napi.Env, as well as methods to access the environment and determine the N-API type of the value.

Implementations of ValueType are expected to bridge Go values with their corresponding N-API representations, facilitating interoperability with Node.js.

Methods:

  • NapiValue(): Returns the underlying primitive napi.Value for N-API calls.
  • NapiEnv(): Returns the associated napi.Env for N-API calls.
  • Env(): Returns the environment as an EnvType.
  • Type(): Returns the N-API type of the value, or an error if it cannot be determined.

func GoFuncOf added in v0.1.2

func GoFuncOf(env EnvType, function any) (ValueType, error)

GoFuncOf wraps a Go function as a JavaScript-compatible function for use with the given environment. It takes an EnvType representing the JavaScript environment and a Go function (of any type). Returns a ValueType representing the JavaScript function and an error if the wrapping fails.

func N_APIValue

func N_APIValue(env EnvType, value napi.Value, extra ...any) ValueType

Return ValueType from napi.Value

func ValueOf added in v0.1.2

func ValueOf(env EnvType, value any) (napiValue ValueType, err error)

ValueOf converts a Go value to its corresponding N-API value representation. It takes an environment handle (env) and a Go value (value) of any type, and returns the resulting N-API value (napiValue) or an error if the conversion fails.

Directories

Path Synopsis
internal
napi
N-API used by sirherobrine23.com.br/Sirherobrine23/napi-go, only use in internal, don't export
N-API used by sirherobrine23.com.br/Sirherobrine23/napi-go, only use in internal, don't export
Package module provides the entry point and initialization logic for N-API modules written in Go.
Package module provides the entry point and initialization logic for N-API modules written in Go.
binding
Export values to Javascript
Export values to Javascript

Jump to

Keyboard shortcuts

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