Best practice for developing Node.js applications

When you are developing Node.js applications, you need to consider using an environment variable to externalize the configuration of a resource. You also need to consider handling the SIGTERM signal in your Node.js application to allow it to terminate gracefully.

Using environment variables

If a Node.js application accesses a resource, such as a TCP/IP port or URI or database, it is recommended to externalize the configuration of that resource using an environment variable. This allows different values to be specified when the application is deployed in development, test, and production environments.

For example, the TCP/IP port to listen for HTTP requests can be specified in the CICS® Node.js application profile:
PORT=8080
The Node.js application can get the value using process.env property:
var httpPort = process.env.PORT

Graceful termination

When a CICS BUNDLE containing a Node.js application is DISABLED, CICS sends the signal SIGTERM to the Node.js process. This gives the Node.js application an opportunity to terminate gracefully. For example, by no longer accepting new connections, stopping persistent connections, completing outstanding requests, and finally closing files and connection to databases, and exiting. The application should terminate within the period specified by option NODEJSAPP_DISABLE_TIMEOUT.

Here's an example of handling the SIGTERM signal and closing an HTTP server:

var http = require('http');
var httpPort = process.env.PORT;
var process = require('process');

//create a server object
var server = http.createServer(
    function (request, response) {
        response.write('Hello World! PID:' + process.pid); //write a response to the client
        response.end(); //end the response
    }
);

process.on('SIGTERM',
    function () {
      server.close(
            function () {
                console.log('Received SIGTERM at ' + (new Date()));
            }
        );
    }
);

console.log("Started hello.js at " + (new Date()));
server.listen(httpPort);

Examples of both of these techniques are demonstrated in the Node.js IVP sample. For more information, see Verifying the installation of the Node.js runtime.