Node JS daemon sample
- daemon.js
var child_process = require('child_process')
function child(exe, args, env) {
var child = child_process.spawn(exe, args, {
detached: true,
stdio: ['ignore', 'ignore', 'ignore'],
env: env
})
child.unref()
return child
}
module.exports = function(nodeBin) {
console.log('Daemonize process')
if (process.env.__daemon) {
return process.pid
}
process.env.__daemon = true
var args = [].concat(process.argv)
var node = args.shift()
var env = process.env
child(node, args, env)
return process.exit()
}
- server.js
var http = require('http')
var daemon = require('./daemon')
daemon()
var http = require("http")
var port = 8090
var host = "127.0.0.1"
var server = http.createServer(
function(request, response){
response.write("Hello World!")
response.end()
})
server.listen(port, host)
Output
$ ./server.js
$ curl -v http://127.0.0.1:8090/
* Trying 127.0.0.1...
* Connected to 127.0.0.1 (127.0.0.1) port 8090 (#0)
> GET / HTTP/1.1
> Host: 127.0.0.1:8090
> User-Agent: curl/7.48.0
> Accept: */*
>
< HTTP/1.1 200 OK
< Date: Wed, 03 Oct 2018 13:52:55 GMT
< Connection: keep-alive
< Transfer-Encoding: chunked
<
* Connection #0 to host 127.0.0.1 left intact
Hello World!