RSS

Tag Archives: parameters

How-to handle app parameters in Node.js

Let say you have to handle one or more custom parameters in your Node.js app. There are many ways to do that, here are my fab 4.
In these examples I’ll read a debug (on/off) and a port (number) parameters.

UPDATED:
keep an eye on these two modules:

 

Passing them to the interpreter

node app.js --debug --port 8080
var dbg = (process.argv.indexOf('--debug') >= 0);
var port = 0;
if (process.argv.indexOf('--port') >= 0 && (process.argv.indexOf('--port')  +1 < process.argv.length))
  port = process.argv.indexOf('--port') + 1;

 

Adding them to the package.json

 ...
 "config": {
   "port": 8080,
   "debug": "true"
 },
 ...
var dbg = (process.env.npm_package_config_debug == 'true');
var port = process.env.npm_package_config_port || 0;

If you’re using PM2, you also need to create an ecosystem.json file (https://keymetrics.io/2014/06/25/ecosystem-json-deploy-and-iterate-faster/) to correctly handle the package.json stuff.

Using a local json file (params.json)

{
  "debug": "true",
  "port": 8080
}
var pars = require('./params.json');
console.log(pars.port, pars.debug);

 

Using an environment variable (not my preferred …)

export debug=true
export port=8080
var dbg = (process.env.debug == 'true');
var port = process.env.port || 0;
Advertisements
 
Leave a comment

Posted by on 2016/07/07 in dev

 

Tags: , ,