Getting started with Node.jsnpmWeb Apps With ExpressFilesystem I/OExporting and Consuming ModulesExporting and Importing Module in node.jsInstalling Node.jsMySQL integrationReadlinepackage.jsonEvent EmittersAutoreload on changesEnvironmentCallback to PromiseExecuting files or commands with Child ProcessesCluster ModuleException handlingKeep a node application constantly runningUninstalling Node.jsnvm - Node Version ManagerhttpUsing StreamsDeploying Node.js applications in productionSecuring Node.js applicationsMongoose Libraryasync.jsFile uploadSocket.io communicationMongodb integrationHandling POST request in Node.jsSimple REST based CRUD APITemplate frameworksNode.js Architecture & Inner WorkingsDebugging Node.js applicationNode server without frameworkNode.JS with ES6Interacting with ConsoleCassandra IntegrationCreating API's with Node.jsGraceful ShutdownUsing IISNode to host Node.js Web Apps in IISCLINodeJS FrameworksgruntUsing WebSocket's with Node.JSmetalsmithParsing command line argumentsClient-server communicationNode.js Design FundamentalConnect to MongodbPerformance challengesSend Web NotificationRemote Debugging in Node.JSMysql Connection PoolDatabase (MongoDB with Mongoose)Good coding styleRestful API Design: Best PracticesDeliver HTML or any other sort of fileTCP SocketsHackBluebird PromisesAsync/AwaitKoa Framework v2Unit testing frameworksECMAScript 2015 (ES6) with Node.jsRouting ajax requests with Express.JSSending a file stream to clientNodeJS with RedisUsing Browserfiy to resolve 'required' error with browsersNode.JS and MongoDB.Passport integrationDependency InjectionNodeJS Beginner GuideUse Cases of Node.jsSequelize.jsPostgreSQL integrationHow modules are loadedNode.js with OracleSynchronous vs Asynchronous programming in nodejsNode.js Error ManagementNode.js v6 New Features and ImprovementEventloopNodejs Historypassport.jsAsynchronous programmingNode.js code for STDIN and STDOUT without using any libraryMongoDB Integration for Node.js/Express.jsLodashcsv parser in node jsLoopback - REST Based connectorRunning node.js as a serviceNode.js with CORSGetting started with Nodes profilingNode.js PerformanceYarn Package ManagerOAuth 2.0Node JS LocalizationDeploying Node.js application without downtime.Node.js (express.js) with angular.js Sample codeNodeJs RoutingCreating a Node.js Library that Supports Both Promises and Error-First CallbacksMSSQL IntergrationProject StructureAvoid callback hellArduino communication with nodeJsN-APIMultithreadingWindows authentication under node.jsRequire()Route-Controller-Service structure for ExpressJSPush notifications

Environment

Other topics

Accessing environment variables

The process.env property returns an object containing the user environment.

It returns an object like this one :

{
  TERM: 'xterm-256color',
  SHELL: '/usr/local/bin/bash',
  USER: 'maciej',
  PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin',
  PWD: '/Users/maciej',
  EDITOR: 'vim',
  SHLVL: '1',
  HOME: '/Users/maciej',
  LOGNAME: 'maciej',
  _: '/usr/local/bin/node'
}
process.env.HOME // '/Users/maciej'

If you set environment variable FOO to foobar, it will be accessible with:

process.env.FOO // 'foobar' 

process.argv command line arguments

process.argv is an array containing the command line arguments. The first element will be node, the second element will be the name of the JavaScript file. The next elements will be any additional command line arguments.

Code Example:

Output sum of all command line arguments

index.js

var sum = 0;
for (i = 2; i < process.argv.length; i++) {
    sum += Number(process.argv[i]);
}

console.log(sum);

Usage Exaple:

node index.js 2 5 6 7

Output will be 20

A brief explanation of the code:

Here in for loop for (i = 2; i < process.argv.length; i++) loop begins with 2 because first two elements in process.argv array always is ['path/to/node.exe', 'path/to/js/file', ...]

Converting to number Number(process.argv[i]) because elements in process.argv array always is string

Using different Properties/Configuration for different environments like dev, qa, staging etc.

Large scale applications often need different properties when running on different environments. we can achieve this by passing arguments to NodeJs application and using same argument in node process to load specific environment property file.

Suppose we have two property files for different environment.


  • dev.json

      {
          PORT : 3000,
          DB : {
              host : "localhost",
              user : "bob",
              password : "12345"
          }
      }
    
  • qa.json

      {
              PORT : 3001,
              DB : {
                  host : "where_db_is_hosted",
                  user : "bob",
                  password : "54321"
              }
      }
    

Following code in application will export respective property file which we want to use.

Suppose the code is in environment.js

process.argv.forEach(function (val, index, array) {
    var arg = val.split("=");
    if (arg.length > 0) {
        if (arg[0] === 'env') {
            var env = require('./' + arg[1] + '.json');
            module.exports = env;
        }
    }
});

We give arguments to the application like following

node app.js env=dev

if we are using process manager like forever than it as simple as

forever start app.js env=dev

How to use the configuration file

 var env= require("environment.js");

Loading environment properties from a "property file"

  • Install properties reader:
npm install properties-reader --save
  • Create a directory env to store your properties files:
mkdir env
  • Create environments.js:
process.argv.forEach(function (val, index, array) {
    var arg = val.split("=");
    if (arg.length > 0) {
        if (arg[0] === 'env') {
            var env = require('./env/' + arg[1] + '.properties');
            module.exports = env;
        }
    }
});
  • Sample development.properties properties file:
# Dev properties
[main]
# Application port to run the node server
app.port=8080

[database]
# Database connection to mysql
mysql.host=localhost
mysql.port=2500
...
  • Sample usage of the loaded properties:
var enviorment = require('./environments');
var PropertiesReader = require('properties-reader');
var properties = new PropertiesReader(enviorment);
   
var someVal = properties.get('main.app.port');
  • Starting the express server
npm start env=development

or

npm start env=production

Contributors

Topic Id: 2340

Example Ids: 7698,10945,22656,31279

This site is not affiliated with any of the contributors.