Configuring a Node.js service in linux
I wanted to set up a simple Node.js web server on a Raspberry Pi, with raspian its pretty straightforward:
Assuming that Node.js is installed on the Pi, the first step is creating the web server, the following code declares a server that exposes information regarding the Raspberry Pi as a JSON, copy the code and create the following file:
"/etc/infoservice/server.js"
//super simple node service that displays server //information:
var os = require("os"),
http = require('http');
//we compose an object with some data:
var osInfo = {
hostname : os.hostname(),
loadavg : os.loadavg(),
uptime : os.uptime(),
freemem : os.freemem(),
totalmem : os.totalmem(),
cpus : os.cpus(),
type : os.type(),
release : os.release(),
arch : os.arch(),
platform : os.platform()
};
//create the server that will respond with the object.
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type':'application/json'});
res.end(JSON.stringify(osInfo));
}).listen(8042);
console.log('server is running');
Once that is done we can configure it as a linux service, so it can run at boot up and has a standard way of starting and stopping.
You will need to copy the following code and create a file here:
"/etc/init.d/infoservice".
#! /bin/sh
### BEGIN INIT INFO
# Provides: Info service
# Required-Start: $remote_fs $syslog
# Required-Stop: $remote_fs $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: a service that provide JSON server description
# Description: a node js server that will publish information on the server, uptime, memory cpu ect.
### END INIT INFO
# Carry out specific functions when asked to by the system
case "$1" in
start)
echo "Starting info service"
# run application you want to start
nodejs /etc/infoservice/server.js & serverpsid=$!
;;
stop)
echo "Stopping info service"
# kill application you want to stop
kill serverpsid
;;
*)
echo "Usage: /etc/init.d/infoservice {start|stop}"
exit 1
;;
esac
exit 0
make sure that the file is executable and run the following command:
$ update-rc.d infoservice defaults
if all worked you can now start the service by running:
$ service infoservice start
And stop it by running:
$service infoservice stop