I have a CLI app made with NodeJS and I can't figure out how to specify NODE_ENV another way than specify it everytime :
NODE_ENV=development myapp
I have two env files : .env.development and .env.production
I have a config files that manage the environment :
import dotenv from "dotenv";
dotenv.config({ path: `.env.${process.env.NODE_ENV}` });
export const config = {
environment: process.env.NODE_ENV,
postgres_host: process.env.POSTGRES_HOST,
postgres_database: process.env.POSTGRES_DATABASE,
postgres_username: process.env.POSTGRES_USERNAME,
postgres_password: process.env.POSTGRES_PASSWORD,
postgres_port: process.env.POSTGRES_PORT,
telegram_api_key: process.env.TELEGRAM_API_KEY,
telegram_chat_id: process.env.TELEGRAM_CHAT_ID
};
And I use my config object when needed :
import { config } from "../config/config.js";
export class Postgres {
static connect() {
this.client = new Client({
host: config.postgres_host,
database: config.postgres_database,
user: config.postgres_username,
password: config.postgres_password,
port: config.postgres_port
});
this.client.connect(function(error) {
if (error) throw error;
console.log("Connected to PostgreSQL");
});
}
...
I'd like to use :
myapp
And set the chosen environment in my index.js file or somewhere else.
#! /usr/bin/env node
import { program } from "commander";
import test from "./commands/test.js";
// Set it by default here maybe ?
program
.command("test")
.description("test")
.action(test);
program.parse();
This is my package.json :
{
"name": "myapp",
"version": "1.0.0",
"description": "Myapp",
"main": "bin/index.js",
"keywords": [
"cli"
],
"bin": {
"myapp": "./bin/index.js"
},
...
Do you have an idea ?
CodePudding user response:
You can set a default environment to use in your config.js
file. When loading your dotenv file, you can specify a default NODE_ENV
value. For example, if you want to use the .env.development
file by default if NODE_ENV
is not specified, you can use the following line to load the dotenv file.
dotenv.config({ path: `.env.${process.env.NODE_ENV || "development"}` });
CodePudding user response:
you can easily say:
myEnv = process.env.NODE_ENV || "development"
and then use myEnv
instead of NODE_ENV
like that:
import dotenv from "dotenv"
myEnv = process.env.NODE_ENV || "development"
dotenv.config({ path: `.env.${ myEnv }` })