I have long running go application, that I want to run from a node process.
package main
import (
"fmt"
"net/http"
)
func main() {
fmt.Println("Running")
http.ListenAndServe(":80", nil)
}
I set up my child process in node like:
async function application(){
//const myProcess = exec("go run main.go");
const myProcess = exec("./main");
myProcess.stdout.on('data', (chunk) => {
console.log(chunk);
})
return new Promise(res => {
setTimeout(() => {
myProcess.on("close", () => {
console.log("close")
res();
});
myProcess.on("exit", () => {
console.log("exit")
})
myProcess.kill();
}, 1000);
})
}
This all works fine if I'm running the compiled binary directly (./main
).
I'll get an output of:
Running
exit
close
(process exits)
However if I try run with go run main.go
my output is
Running
exit
(process continues)
Specifically what is happening here that the go run
process will not close properly?
My understanding is that this is going to come down to the difference between 'close' and 'exit' events.
From the documentation:
The 'close' event is emitted after a process has ended and the stdio streams of a child process have been closed. This is distinct from the 'exit' event, since multiple processes might share the same stdio streams. The 'close' event will always emit after 'exit' was already emitted, or 'error' if the child failed to spawn.
Ok, so maybe something about go run leaving a stdio stream open? That's where my understanding is unclear.
For the problem I'm solving, just using the binary will work fine.
But I'm curious, if I did want to use the go run
process - how would I close it properly?
Repro for this here: GitHub.