How to add database environment variables to Javascript - 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.

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"

How to run node js application without terminal command

I'm so new in node.js and I have a simple node.js project with only one js file (vpn.js) which use a module and an index.html which opens using a function in vpn.js. I have installed this package and the require function can find its module. I have a vpn.js file and an index.html (in index.html I only have a video tag with a src.). Now my question is should I always run my code with terminal? how should I host this project? Basically no clients can run terminal commands on web. (note: I'm using Windows not Linux)
this is the code of my js file:
const openvpnmanager = require('node-openvpn');
const opts = {
host: '192.168.1.7', // normally '127.0.0.1', will default to if undefined
port: 8080, //port openvpn management console
timeout: 1500, //timeout for connection - optional, will default to 1500ms if undefined
logpath: 'log.txt' //optional write openvpn console output to file, can be relative path or absolute
};
const auth = {
user: 'vpnUserName',
pass: 'vpnPassword',
};
const openvpn = openvpnmanager.connect(opts)
// will be emited on successful interfacing with openvpn instance
openvpn.on('connected', () => {
//openvpnmanager.authorize(auth);
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
fs.readFile('index.html', function(err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
return res.end();
});
}).listen(5500);
});
// emits console output of openvpn instance as a string
openvpn.on('console-output', output => {
console.log(output);
});
// emits console output of openvpn state as a array
openvpn.on('state-change', state => {
console.log(state)
});
// emits console output of openvpn state as a string
openvpn.on('error', error => {
console.log(error)
});
Use pkg npm package. This will create an executable file for your nodejs project. You can create executable file for Windows or mac or linux.
Install pkg globally using following command
npm install -g pkg
After installing it, use:
pkg app.js[entry file to your project] to create executable file.
For more info about pkg, look into pkg
you can done it help of set autorun the node server forever.
here is some step
You may also want to consider using the upstart utility. It will allow you to start, stop and restart you node application like a service. Upstart can configured to automatically restart your application if it crashes.
Install upstart:
sudo apt-get install upstart
Create a simple script for your application that will look something like:
#!upstart
description "my app"
start on started mountall
stop on shutdown
# Automatically Respawn:
respawn
respawn limit 99 5
env NODE_ENV=production
exec node /somepath/myapp/app.js >> /var/log/myapp.log 2>&1
Then copy the script file (myapp.conf) to /etc/init and make sure its marked as executable. Your application can then be managed using the following commands:
sudo start myapp
sudo stop myapp
sudo restart myapp

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 do i connect an existing database to sequelize.js?

I have a database I generated through postgres. How do I connect it to sequelize for node.js?
I know the basic syntax for sequelize connections, but how do I connect these together?
In node.js after installing the sequelize and pg packages through npm you can do this:
var sequelize = new Sequelize('your_database_name', 'user', 'password', {
host: "localhost", //your server
port: 12345 //server port
dialect: 'postgres'
});
Note, in order to use Sequelize with Postgres you'll_need the postgres package. The Sequelize homepage contains instructions on changes you might need to make in order to use them together.

nodejs .env variable undefined

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
})

Categories

Resources