-1

I have a coding like this

var express = require('express');
var app=express();
var mongodb = require('mongodb');
var Db=require('mongodb').Db;
var Server=require('mongodb').Server;
var client=new Db('healthdata' , new Server('127.0.0.1',27017),{safe:false});

client.open(function(err,pClient)
{
  client.collection('userdetails',function(err,collection)
  {
    Ucollection=collection;
  });
});

app.listen(8080,'192.168.0.1');

I have run my application by using port and local ip address like above so how to set environment variable for hostnames and port for both node and mongodb. explain me with coding.

ultranaut
  • 2,132
  • 1
  • 17
  • 22
silvesterprabu
  • 1,417
  • 10
  • 30
  • 46

1 Answers1

10

Node.js is able to access environment variables using process.env.XXX where XXX is the name of the variable you want to access.

One usual solution for your question is to define an environment variable, e.g. PORT which contains the port number, and then access it as process.env.PORT.

As you can not guarantee that this environment variable is set under every circumstance, you'll usually also include a fallback, such as:

var port = process.env.PORT || 3000;

For the IP address, it's basically the same:

var ip = process.env.IP || '192.168.178.1';

Then you can do:

var ip = process.env.IP || '192.168.178.1',
    port = process.env.PORT || 3000;

app.listen(port, ip);

Hope this helps.

Golo Roden
  • 140,679
  • 96
  • 298
  • 425