nodejs .env variable undefined - javascript

I am getting undefined when trying to get the value from .env
Here is my server.js
console.log(process.env.val);
Here is my .env file
val=hello
Screenshot that shows the file hierarchy
When I run the server I get undefined. How to fix?

You need to use dotenv library
Create a .env file in the root directory of your project. Add environment-specific variables on new lines in the form of NAME=VALUE. For example:
DB_HOST=localhost
DB_USER=root
DB_PASS=s1mpl3
That's it.
process.env now has the keys and values you defined in your .env file.
var db = require('db')
db.connect({
host: process.env.DB_HOST,
username: process.env.DB_USER,
password: process.env.DB_PASS
})

Related

Autodesk Forge web application - from visual studio code to close .exe file

I have a working forge application ( bim360 hub sidebar with forge viewer and some charts).
It is currently running from Visual Studio Code IDE only. I want to build the app into an .exe file in order to be able to send it to a user, upload it to a server with IIS, etc..
General details:
I used Petr Broz tutorial to set up the backend of the viewer and hub
(Forge online training - view your models https://www.youtube.com/watch?v=-O1e3gXCOEQ&t=8986s )
The app is running on Node.js
I tried to use 'nexe' module and build executable file. With this method, I need to specify index.js file ("an entry point") and define a 'nexe.config.js' file. I used the entry point start.js.
Eventually, I managed to create an exe file - and when I run it from the command line, I get an error
Missing FORGE_CLIENT_ID or FORGE_CLIENT_SECRET env. variables.
although I have them in the config.js
Main questions:
Is there another way to build a close exe file from visual studio code - for a forge web application?
Am i doing something wrong with the processes I mention above?
Is it even possible to deploy a web application to IIS using an exe file?? all of the documentation points toward Azur, AWS and heroku..
Relevant files:
1) start.js:
const path = require('path');//bringing in built in node js modeules ( to resulve file system path )
const express = require('express');//module to create the express server
const cookieSession = require('cookie-session');
//any piece of code would have an opportunity to handle the request
const PORT = process.env.PORT || 3000;
const config = require('./config.js');
if (config.credentials.client_id == null || config.credentials.client_secret == null) {
console.error('Missing FORGE_CLIENT_ID or FORGE_CLIENT_SECRET env. variables.');
return;
}
let app = express();
//static middlewere to check for the front end files (html,js,css)
app.use(express.static(path.join(__dirname, 'public')));//method inside express module: a middlewere for serving static files this line will check in 'public' folder if the request
//that is sent (specific file) is in there. if so - it will ignore the rest of the stack(the rest of the code)
app.use(cookieSession({
// create 2 cookies that stores the name and encripted key
name: 'forge_session',
keys: ['forge_secure_key'],//takes cater of decipher the encription for the forge key for us
maxAge: 14 * 24 * 60 * 60 * 1000 // 14 days, same as refresh token
}));
app.use(express.json({ limit: '50mb' }));//middlewere that looks at the title of the request - and if its .json it will look at the body of the request and parese it to javascript object
app.use('/api/forge', require('./routes/oauth.js'));//adding our custom express routers that will handle the different endpoints.
app.use('/api/forge', require('./routes/datamanagement.js'));
app.use('/api/forge', require('./routes/user.js'));
app.use((err, req, res, next) => {
console.error(err);
res.status(err.statusCode).json(err);
});
app.listen(PORT, () => { console.log(`Server listening on port ${PORT}`); });
2) config.js:
// Autodesk Forge configuration
module.exports = {
// Set environment variables or hard-code here
credentials: {
client_id: process.env.FORGE_CLIENT_ID,
client_secret: process.env.FORGE_CLIENT_SECRET,
callback_url: process.env.FORGE_CALLBACK_URL
},
scopes: {
// Required scopes for the server-side application-->privliges for our internal opperation in the server side ("back end")
internal: ['bucket:create', 'bucket:read', 'data:read', 'data:create', 'data:write'],
// Required scope for the client-side viewer-->priveliges for the client ("front end")
public: ['viewables:read']
}
};
Author of the tutorial here :)
I'm not sure how nexe works exactly but please note that the sample app expects input parameters such as FORGE_CLIENT_ID or FORGE_CLIENT_SECRET to be provided as environment variables.
As a first step, try running your *.exe file after setting the env. variables in your command prompt.
If that doesn't work, try hard-coding the input parameters directly into the config.js file (replacing any of the process.env.* references), and then bundle everything into an *.exe file. This is just for debugging purposes, though! You shouldn't share your credentials with anyone, not even inside an *.exe file. So as an alternative I'd suggest that you update the sample app to read the input parameters from somewhere else, perhaps from a local file.
after trying a lot of solutions, i got to the conclusion that the reason that nothing happened was that the oathantication files ( with the clint_id and clint_password) was not embedded in the .exe file.
the way to include those files with the nexe module is to use the flag -r "Foldername/subfoldername/filename.js".
first, crate a nexe.config.js file that would contain the entry point file name to the app. ( in my case, the file name is " start.js")
second, write the following commands in the command line:
cd C:\Projects\MyAppFolder
npm install -g nexe
// specify all the files you want to include inside the exe file
nexe start.js -r "config.js" -r "nexe.config.js" -r "routes/common/oauth.js" -r "routes/*.js" -r "public//." -r ".vscode/**/." -r "package-lock.json" -r "package.json" --build --output "AppName.exe"

I can not use env file variable values in my node project

I have 2 variables in env file. For Port and mongoDB link. I have tried many solutions on the internet but i am not able to access the values in the listen method nor in database connection.
Here is my sever file code:
const app = require("./app");
const connectDatabase = require("./config/database");
// Config
require("dotenv").config({ path: "backend/config/config.env" });
// Connecting to database
connectDatabase();
app.listen(process.env.PORT, () => {
console.log(`Server is working on http://localhost:${process.env.PORT}`);
}); // I can run the app if i use any port number in place of "process.env.PORT"
Note: I have put the wrong password here to hide my credentials.
I have tried to use env file in root directory also but it did not resolve the issue. The thing is i can access the values in the console but not in the listen method or in connection method.
I can run the app with direct values.
Here is the listen method error screenshot:
Right now you are passing 3000; to the listen function, you need to pass 3000.
Remove the semicolons ; from the env file and it should work.
Have a look at the dotenv npm page here for examples.
Also, you have posted your mongodb credentials online, I'd suggest you change those immediately.

Config File in NodeJS using npm config

I have a on-cloud SAAS application built on Angular/NodeJS/Postgres+MongoDB stack that can connect to customer DB, cloud warehouses, S3 buckets etc to load information. Once I get the connection information from Angular front-end I need to store this information for future retrieval .
Example :
Angular Front-end
<form>
Database Type :
Host :
Port :
Username:
Password :
S3Bucket :
Region :
bucket-name :
Access key :
</form>
etc.
I need this information saved for later access. As suggested by Abdullah Deliogullari in the original question, I am trying to use config module npm config. But how do I use package config to write config file and load it in a running application.
ie While my application is running I need to write the (say S3) bucket info to a customer.config file (from frontend JSON) and later when required to retrieve data use the customer.config to connect to S3 bucket.
The "get" portion I am able to understand but the write portion (adding a new section dynamically) is what I am not able to figure out.
Example from frontend when I pass in the values like
["ct_postgres":
{"host":"3.15.xxx.xxx",
"port":"5132",
"dbname":"wcdb"
}]
this should be written to the config file. So something like config.put/write I am looking for. Next time I want to make connection to the customer postgresdb I do config.get() and it provides me the connection details.
Original question
First you should install this package
npm install config
After that create config file into your project directory(name "config" is a must).
In this file create development.json and production.json files(these names are optional). Content of development.json could be like this
{
"SERVER" : {
"port" : 5000
},
"PASSWORDHASH" : {
"saltRounds" : 10
}
}
In your javascript file for example in app.js file, first you should include the library, and then you can get configuration informations via this module
const config = require('config');
const port = config.get("SERVER.port");
app.listen(port);
Last step should be add this development.json file name to NODE_ENV variable
NODE_ENV=development node app.js
So if you want to update your json file based on new data coming from your frontend, you can basically do this
var fs = require('fs');
var file_content = fs.readFileSync("development.json");
var content = JSON.parse(file_content);
content.SERVER.port = 6000;
fs.writeFileSync("development.json", JSON.stringify(content));

RequireJs doesn't work with mysql variable

I have a little Problem with RequireJs. When i load the index.js of mysql as a mysql variable and create a connection with it, then it says: Uncaught ReferenceError: createConnection is not defined. This is the code i use it in:
var mysql = requirejs(['mysql/index.js']);
var connection = mysql.createConnection({
host: 'myhost',
user: 'myuser',
password: 'mypassword',
database: 'mydatabase'
})
The javascript code is in the index.js of the directory js. And i use it in index.html.
The hierarchy
What did i wrong? I don't use the normal require because i can't call it with node and it doesn't work without it.
Thank you for any help.
https://www.npmjs.com/package/mysql is a NPM package so it uses CommonJS module format. It is possible to use CommonJS packages with RequireJS, please read more in the docs: https://requirejs.org/docs/commonjs.html

How to add database environment variables to Javascript

I want to add my database environment variables to a .env file and use that file in my Javascript program in order to create a connection to my database using Node.js.
So here is my database info which I use to create connection with:
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "my password",
database: "mydatabase"
});
Then I try to check if I am connected to my database using these lines:
(It should print "Connected!").
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
I want to put the first block of code in another file and require that file in my Node.js program.
How should I do this? How should I require the file? Thank you in advance :)
I suggest using dotenv package.
Taken straight from the readme:
As early as possible in your application, require and configure dotenv.
require('dotenv').config()
Create a .env file in the root directory of your project. Add
environment-specific variables on new lines in the form of NAME=VALUE. For example:
DB_HOST=localhost
DB_USER=root
DB_PASS=s1mpl3
Usage (process.env now has the keys and values you defined in your .env file.)
var db = require('db')
db.connect({
host: process.env.DB_HOST,
username: process.env.DB_USER,
password: process.env.DB_PASS
})
NOTE: Make sure your .gitignore has an entry to ignore .env files.
You can use a module called dotenv which will load an environments variables defined in a .env file or any file you specify. You would then load the .env in two ways:
In the main script file, call require('dotenv').config()
Via npm script: "dev": "node -r dotenv/config app.js"
Either works, but you do not want to commit .env to source control. Always keep sensitive credentials out. You can create a an .env.example to alert new users the required variables.
Using dotenv package. Install dotenv package.
npm i dotenv
Create a new .env file in project root directory.
touch .env
Add environment variables to .env file
API_HOST=HOST-PLACEHOLDER-URL
API_KEY=TOP-SECRET
APP_NAME=node_crud
APP_ENV=local
APP_KEY=base64:RIjL2Uw/Wdve+HJEvRNp6LHhzoHtLbplQcUp60CBIvs=
APP_DEBUG=true
APP_URL=http://localhost
LOG_CHANNEL=stack
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=node_restapi
DB_USERNAME=root
DB_PASSWORD=
PORT = 5000
Add config/database.js file
const dotenv = require('dotenv');
const mysql = require('mysql');
// configraration with env.
dotenv.config();
module.exports = mysql.createConnection({
host: process.env.DB_HOST,
user: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
database: process.env.DB_DATABASE
});
config/database.js connect with app.js file
// Database Connection
const conn = require('./config/database');
// Shows Mysql Connect
conn.connect((err) =>{
if(err) throw err;
console.log('Mysql Connected with App...');
});
A .env file is needed for a clean separation of environment-specific configurations.
The dotenv packaged is used to read a .env file at runtime containing environment variables and append them on the process.env object.
Creating an example for a .env file to document the mandatory variables speeds up project setup time.
Never commit a .env file to version control.

Categories

Resources