Giter Club home page Giter Club logo

go-node's Introduction

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.

go-node's People

Contributors

tidwall avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.