從Go執行JavaScript

v8go

從Go執行JavaScript

v8go - 從Go執行JavaScript

V8依賴

V8版本:7.6.303.31

為了使其v8go可用作標準Go包,可以為Linux和OSX包含預構建的V8靜態庫。

V8需要64位,因此無法在32位系統上運行。

用法

import "rogchap.com/v8go"

運行腳本

ctx, _ := v8go.NewContext(nil) // creates a new V8 context with a new Isolate aka VM
ctx.RunScript("const add = (a, b) => a + b", "math.js") // executes a/>ctx.RunScript("const result = add(3, 4)", "main.js") // any functions previously added to the context can be called
val, _ ctx.RunScript("result", "value.js") // return a value in JavaScript back to Go
fmt.Printf("addition result: %s", val)

一個VM,很多情況

vm, _ := v8go.NewIsolate() // creates a new JavaScript VM
ctx1, _ := v8go.NewContext(vm) // new context within the VM
ctx1.RunScript("const multiply = (a, b) => a * b", "math.js")

ctx2, _ := v8go.NewContext(vm) // another context on the same VM
if _, err := ctx2.RunScript("multiply(3, 4)", "main.js"); err != nil {
// this will error as multiply is not defined in this context
}

Javascript錯誤

val, err := ctx.RunScript(src, filename)
if err != nil {
err = err.(v8go.JSError) // JavaScript errors will be returned as the JSError struct
fmt.Println(err.Message) // the message of the exception thrown
fmt.Println(err.Location) // the filename, line number and the column where the error occured
fmt.Println(err.StackTrace) // the full stack trace of the error, if available

fmt.Printf("javascript error: %v", err) // will format the standard error message
fmt.Printf("javascript stack trace: %+v", err) // will format the full error stack trace
}

更多使用文檔可以看官方資料

v8go - 從Go執行JavaScript

開源地址:

由於頭條審核網址比較嚴,防止他們誤會是推廣,所以大家可以自行搜索下載

也可以關注我的頭條號後給我發送 `v8go`,會自動把下載地址發送給你(做了關鍵字自動回覆)

您知道哪些好用的小工具,歡迎評論分享,共同探討學習

更多更優質的資訊,請關注我,你的支持會鼓勵我不斷分享更多更好的優質文章。


分享到:


相關文章: