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:


//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'});
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:


#! /bin/sh

# 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.

# Carry out specific functions when asked to by the system
case "$1" in
       echo "Starting info service"
       # run application you want to start
       nodejs /etc/infoservice/server.js & serverpsid=$!
      echo "Stopping info service"
      # kill application you want to stop
      kill serverpsid
      echo "Usage: /etc/init.d/infoservice {start|stop}"
      exit 1

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