node

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Feb 3, 2021 License: MIT Imports: 13 Imported by: 0

README

go-node

GoDoc

Run Javascript in Go using Node.js.

Installing

go get -u github.com/tidwall/go-node

Examples

Create a Node.js VM and run some Javascript.

vm := node.New(nil)
vm.Run("iLoveTheJS = true");
youLoveIt := vm.Run("iLoveTheJS")
println(youLoveIt.String()) 

// output: 
// true

The Run function runs any Javascript code and returns a Value type that has two methods, String and Error. If the Run call caused a Javascript error then the Error method will contain that error. Otherwise, the String method will contain the Javascript return value.

vm := node.New(nil)
vm.Run(`
  function greatScott(){ 
    console.log('1.21 gigawatts?');
    return 'Delorean go vroom';
  }
`);
v := vm.Run("greatScott()");
if err := v.Error(); err != nil {
    log.Fatal(err)
}
println(v.String())

// output:
// 1.21 gigawatts?
// Deloran go vroom

You can "emit" messages from the Javascript to the Go. It's easy. Just use the Options.OnEmit method in Go, and call the emit() function from JS.

opts := node.Options {
    OnEmit: func(thing string) {
        println(thing)
    },
}
vm := node.New(&opts)
v := vm.Run("emit('a thing')")
if err := v.Error(); err != nil{
    log.Fatal(err)
}

// output: 
// a thing

Yay 🎉. Have fun now.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ErrThrown

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

ErrThrown is returned where the input script from Run() throws a Javascript error.

func (ErrThrown) Error

func (err ErrThrown) Error() string

type Options

type Options struct {
	// OnEmit is an optional callback that handles emitted messages.
	OnEmit func(thing string)
	// OnConsoleLog is an optional callback that handles notice messages that
	// are intended for the console logger.
	OnLog func(msg string)
	// OnConsoleError is an optional callback that handles error messages that
	// are intended for the console logger.
	OnError func(msg string)
	// Dir is the working directory for the VM. Default is the same working
	// directory and currently running Go process.
	Dir string
	// Flags are the additional startup flags that are provided to the
	// "node" process.
	Flags []string
}

Options for VM

type VM

type VM interface {
	Run(javascript string) Value
}

VM is a Javascript Virtual Machine running on Node.js

func New

func New(opts *Options) VM

New returns a Javascript Virtual Machine running an isolated process of Node.js.

type Value

type Value interface {
	// Error returns an error, if any.
	Error() error
	// String returns the string representation of the Value.
	String() string
}

Value is the returned from Run().

Jump to

Keyboard shortcuts

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