Package go2node provides a simple API to inter-process communicating for go and node.
go2node will CREATE or RUN AS Node child process with Node IPC protocol.
- Golang ≥ 1.12.x
- Node.js ≥ 8.x
main.go:
package main
import (
"fmt""os""os/exec""github.com/zealic/go2node"
)
funcmain() {
cmd:=exec.Command("node", "child.js")
cmd.Stdout=os.Stdoutcmd.Stderr=os.Stderrchannel, err:=go2node.ExecNode(cmd)
iferr!=nil {
panic(err)
}
defercmd.Process.Kill()
// Node will output: {hello: "node"}channel.Write(&go2node.NodeMessage{
Message: []byte(`{"hello": "node"}`),
})
// Golang will output: {"hello":"golang"}msg, err:=channel.Read()
iferr!=nil {
panic(err)
}
fmt.Println(string(msg.Message))
// Wait node child process exitcmd.Process.Wait()
}child.js:
process.on('message',function(msg,handle){console.log(msg);process.exit(0);});process.send({hello: 'golang'});Run go run main.go to test.
Output:
{"hello":"golang"}
{ hello: 'node' }
main.js:
constchild_process=require('child_process');letchild=child_process.spawn('go',['run','gochild.go'],{stdio: [0,1,2,'ipc']});child.on('close',(code)=>{process.exit(code);});child.send({hello: "child"});child.on('message',function(msg,handle){if(msg.hello==="parent"){console.log(msg);process.exit(0);}process.exit(1);});gochild.go:
package main
import (
"fmt""github.com/zealic/go2node"
)
funcmain() {
channel, err:=go2node.RunAsNodeChild()
iferr!=nil {
panic(err)
}
// Golang will output: {"hello":"child"}msg, err:=channel.Read()
iferr!=nil {
panic(err)
}
fmt.Println(string(msg.Message))
// Node will output: {"hello":'parent'}err=channel.Write(&go2node.NodeMessage{
Message: []byte(`{"hello":"parent"}`),
})
iferr!=nil {
panic(err)
}
}Run node ./main.js to test.
Output:
{"hello":"child"}
{ hello: 'parent' }
- https://github.com/nodejs/node/blob/master/lib/child_process.js
- https://github.com/nodejs/node/blob/master/lib/internal/child_process.js
- https://github.com/nodejs/node/blob/master/src/stream_wrap.cc
- https://github.com/libuv/libuv/blob/master/src/unix/stream.c
- https://medium.com/js-imaginea/clustering-inter-process-communication-ipc-in-node-js-748f981214e9