Node.js instance family

This instance family is for webmasters who need to host a dynamic website written in Node.js.

Prerequisites

  • Knowledge of Node.js and the HTTP protocol,
  • Your site must use NPM to handle its dependencies

Version support

We use versions 0.8.x and 0.10.x for the moment; Node.js does not really manage life cycles for the various branches, so it is difficult to know for how long we will be able to support a given version. The default version is always the latest one among those installed, currently 0.10.x. To choose the Node.js version to execute your application, see Selection of Node.js version.

General functioning

Your Node.js application must be composed of at least a file called server.js. This file will be executed by the Node.js interpreter when your instance is started, or during a deployment with the Git access. In order to receive HTTP requests, your application must listen to port specified by the environment variable PORT (process.env.PORT).

vhosts

Contrary to PHP instances, each creation of a vhost does not create a specific directory on your disk. The directory named “default” present in your vhosts allows you to manage the data for your Node.js instance. Only one instance of your application is executed, and must manage all the vhosts that you have associated to your Simple Hosting instance.

Examples

Here is an a simple Node.js application that displays the name of the vhost

server.js

var http = require('http');
http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.write('Hello Node.js!\n');
    if ('host' in req.headers) {
        var host = req.headers['host'];
        res.write('Vhost is ' + host.split(':')[0] + '\n');
    } else {
        res.write('No vhost specified\n');
    }
    res.end();
}).listen(process.env.PORT);

You can see a vhost example with express.js at https://github.com/visionmedia/express/blob/master/examples/vhost/index.js

Dependencies installation of your site

The Node.js Simple Hosting platform takes care of the booting of your instance during a deployment via your Git access, and installing the dependencies of your website. For this, you must specify the dependencies in the “package.json” file at the root of your vhost:

package.json

{
  "name": "website",
  "version": "0.0.1",
  "dependencies": {
    "express": "3.x"
  }
}

Selection of Node.js version

It is possible to choose the Node.js version to execute your application among those available. To do this, simply specify in the file “package.json” the Node.js version you want using the field “engines”.

package.json

{
  "name": "website",
  "version": "0.0.1",
  "engines": {
    "node": "< 0.10"
  }
}

The example above will force the use of Node.js 0.8.x. For more information about the field “engines”, see https://npmjs.org/doc/json.html#engines.

Logs

The standard output and errors of your website are sent to a log file on your disk:

  • via the SSH console: /srv/data/var/log/www/nodejs.log
  • via SFTP: /lamp0/var/log/www/nodejs.log

This log file also contains the output of the NPM program that is in charge of your website's dependencies.

Additionally, you can view the history of actions taken by the program in charge of launching your site:

  • via the SSH console: /srv/data/var/log/www/nodejs-watchd.log
  • via SFTP: /lamp0/var/log/www/nodejs-watchd.log

You can also see if your Node.js application has correctly booted.

Database

MySQL

    connection: {
        socketPath: '/srv/run/mysqld/mysqld.sock',
        user: 'user',
        password: 'pwd',
        database: 'db',
        charset: 'utf8'
    }

Full example:

var mysql = require('mysql');
var connection = mysql.createConnection({
socketPath: '/srv/run/mysqld/mysqld.sock',
user: 'myUser',
password : 'myPassword',
database: 'myDB'
});
connection.connect(function(err) {
        if(err) {
                console.log(err.code);
        } else {
        console.log('connected...');
        }
});
connection.end();

PostgreSQL

At the moment, the Node.js instance comes with the PostgreSQL database. Note that PostgreSQL9.2 now supports the JSON data type; meaning that you can now directly store JSON data fields. You can also manipulate existing tables and output its data to clients as JSON using array_to_json and row_to_json functions.

Full example to use Node.js with PostgreSQL:

server.js

var http = require('http');
var pg = require('pg');
 
var conString = "tcp://pguser:password@localhost/mycms";
 
function list_articles(callback) {
    var client = new pg.Client(conString);
    client.connect(function(err) {
        if (err) {
            callback(null, err);
        } else {
            client.query('SELECT * FROM articles ORDER BY art_id DESC;',
                         callback);
        }
    });
}
 
function handle_error(res) {
    res.writeHead(500, {'Content-Type': 'text/plain'});
    res.end('Internal Server Error\n');
}
 
function write_response(res, result) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.write('Number of articles: ' + result.rowCount + '\n');
    result.rows.forEach(function(row) {
        res.write(row.art_id + ' | ' + row.art_title + '\n');
    });
    res.end();
}
 
server = http.createServer(function(req, res) {
    list_articles(function(err, result) {
        if (err) {
            console.log(err);
            handle_error();
        } else {
            write_response(res, result);
        }
    });
});
 
server.listen(process.env.PORT);

package.json

{
  "name": "website",
  "version": "0.0.1",
  "dependencies": {
    "pg": "0.x"
  }
}

MongoDB

It is now possible to create Node.js/mongoDB instances.

Known issues

PostgreSQL

The installation of the pg module does not work with the npm version that is delivered with Node.js 0.10.x. It is therefore recommended that you chose version 0.8.x de Node.js, by following the instructions in the section concerning the choice of your Node.js version.

While installing pg module, the following errors messages might show up:

gyp WARN EACCES user "root" does not have permission to access the dev dir "/srv/data/.node-gyp/0.8.22"
gyp WARN EACCES attempting to reinstall using temporary dev dir "/srv/data/tmp/.node-gyp"
You need to install postgresql-server-dev-X.Y for building a server-side extension or libpq-dev for building a client-side application.
gyp: Call to 'pg_config --libdir' returned exit status 1. while trying to load binding.gyp
gyp ERR! configure error 
gyp ERR! stack Error: `gyp` failed with exit code: 1
gyp ERR! stack     at ChildProcess.onCpExit (/usr/lib/node_modules/npm/node_modules/node-gyp/lib/configure.js:416:16)
gyp ERR! stack     at ChildProcess.EventEmitter.emit (events.js:99:17)
gyp ERR! stack     at Process._handle.onexit (child_process.js:678:10)
gyp ERR! System Linux 3.4.7-grsec-paas-19c573d
gyp ERR! command "node" "/usr/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /srv/data/web/vhosts/default/node_modules/pg
gyp ERR! node -v v0.8.22
gyp ERR! node-gyp -v v0.8.5
gyp ERR! not ok 

The pg module is in fact installed, but will be limited to the Javascript implementation. The fix will be present in the next release.

Websockets

We don't support websockets, as Simple Hosting aims to be an HTTP(S) service.

See also

上一次變更: 2016/05/31 10:23 (外部編輯)