Isaac Krementsov
Isaac Krementsov

Reputation: 706

Is it possible to "save" a variable value in NodeJs?

I have a website where I want the client to be able to make their site go live by setting var live = true;, and then setting webpages to display if it is true. I don't want to save the live variable in a database (a collection solely for that would not make sense). Is there a way to assign a permanent value to the variable in NodeJS?

Upvotes: 0

Views: 7368

Answers (5)

you can app it to process variable like this :

process.live = true  ; 

then you can access it in anywhere in system , but if you run two system you will can change process.live value from the other system becouse process object save

Upvotes: 0

plgladio
plgladio

Reputation: 1

If the variable is going to be changing for different users have it store in a JSON file against user id. Consider DiskDb JSON file but can be used as Query.

Upvotes: 0

Manjeet Singh
Manjeet Singh

Reputation: 2398

You can use YAML module in nodejs.

default:
  server:
    port: 6379                # server port
    live: true                # option for live

You can read these values and write on these values. it is faster and safe method and kind of small database which is you want

https://www.npmjs.com/package/yaml-config

Upvotes: 0

Pubudu Dodangoda
Pubudu Dodangoda

Reputation: 2874

Of course you can use environment variables. When starting the NodeJs service, you can pass variables like this,

LIVE=true node server.js 

Then access it from the app from anywhere like this,

var live = process.env.LIVE

However, I would recommend using environment specific configuration files for your purpose. By doing so, you can change the LIVE variable based on the execution environment (QA, DEV, STAGING, PRODUCTION, etc)

You can define a json file with the configurations you need,

{
    "LIVE": true,
    // More variables can be defined here
}

And store the files in an absolute path(not in the local repo), like /usr/local/my_configs/ or /etc/my_confs/.

Then import or require the config files similar to how you would require a .js file.

like this,

var my_config = require('/etc/my_confs/my_conf.json');
const LIVE = my_config.LIVE;

Upvotes: 2

Gnanesh
Gnanesh

Reputation: 718

You can't exactly save it, but read from your environment file (or) environment variables. Like .env.

To change the variable, you must configure the environment variables.

.env(Local):

LIVE=TRUE

In the cloud, you would have GUI settings, where you can configure the variables.

Then you can simply set the variable to:

var live = process.env.LIVE;

Ask your client to manually set the variable. Mostly you have to restrict their accessibility

Upvotes: 0

Related Questions