How dotenv Package Work With pg.Pool in NodeJS - javascript

I've read some code that uses the dotenv package to create configurations.
When I read a file that contains PostgreSQL code for Pool, the code looks like this:
const pg = require('pg')
const { Pool } = pg
// This pool was created without completing the pool connection configuration. 
const pool = new Pool()
However, I see that this pool configuration is written in the.env file. 
#POOL CONFIGURATIONS
PGUSER=username
PGPASSWORD=password
PGHOST=localhost
PGDATABASE=databasename
PGPORT=5432
and .env file is called once in main file :
// main file
require('dotenv').config()
const express = require('express')
// below is the server
Why is a pool created without passing any configuration objects as arguments?
How does it work in the background?
I still can't figure this out clearly.
I've tried searching for this behavior, but I haven't found it yet.

When you run
require('dotenv').config()
that sets everything in your .env file to be on process.env.*.
For example, you say PGUSER=username, so now process.env.PGUSER === "username"
pg.Pool seems to go with those environment variables by default

Related

How to solve error EROFS: read-only file system, open '/var/task/db.json'?

const jsonServer = require('json-server')
const cors = require('cors')
const path = require('path')
const server = jsonServer.create()
const router = jsonServer.router(path.join(__dirname, 'db.json'))
const middlewares = jsonServer.defaults()
server.use(cors())
server.use(jsonServer.bodyParser)
server.use(middlewares)
server.use(router)
const PORT = 8000
server.listen(PORT, () => {
console.log(`JSON Server is running on http://localhost:${PORT}`)
})
I am using cyclic.sh for deployment. How to solve this error?
I was trying to deploy a json-server. And while doing a post request I got this error.
Taking as a starting point that you shouldn't use a tool like json-server in production environments, I could understand you might be using it for demo purposes. That case, there are some serverless solutions which prevents your code from open files in write mode, so that's why the jsonServer.router(...) line fails its execution.
If you don't matter about that db.json file being updated by the requests (because anyway, your deployment solution doesn't seem to allow it), you could just use instead a js object, that can be modified in memory (but, of course, the json file will still keep intact). So, instead of:
const router = jsonServer.router(path.join(__dirname, 'db.json'))
try using something like:
const fs = require('fs')
const db = JSON.parse(fs.readFileSync(path.join(__dirname, 'db.json')))
const router = jsonServer.router(db)

Connecting to MongoDB database

I am trying to connect to a MongoDB database.I have followed all the steps here https://youtu.be/EcJERV3IiLM but am getting an error.
The index.js file looks like this,
const dotenv = require('dotenv')
dotenv.config()
const mongodb = require('mongodb')
mongodb.connect(process.env.CONNECTIONSTRING, async function(err,client){
const db = client.db()
const results = await db.collection("student").find().toArray()
console.log(results)
The error I get is,
mongodb.connect is not a function
So it seems to be reading as far line 5:9 which is mongodb.connect in index.js and just stops.
I put this file index.js beside the .env file and beside that .gitignore which contains the the .env file. The .env file has the code which I copied from the Mongodb AtlSAS Cloud Service.
I also created a user and and autogenerated and saved a password. Both of which I placed in the string. And I put in the string the name of the database name "blah" The table/document is called "student". That's in the index.js code above. So the database name and the document name are blah.student.
I documented what I tried here, http://www.shanegibney.com/shanegibney/mongodb-setup/
The tutorial video is here, https://youtu.be/EcJERV3IiLM
I am on Ubuntu Linux.
I am currently running index.js in the terminal in a directory called mongostack, with
node index.js
but should I use,
nodemon index.js
And for this should I install nodemon and how do I do that?
Do I need to download it first and if so where do I get it?
I think you need to get MongoClient. Try changing:
const mongodb = require('mongodb')
to:
const mongodb = require('mongodb').MongoClient;
You have to create a MongoClient see https://www.mongodb.com/docs/drivers/node/current/quick-start/
const { MongoClient } = require("mongodb");
const uri = process.env.CONNECTIONSTRING;
const client = new MongoClient(uri);
async function run() {
await client.connect();
const db = client.db("yourdb")
const results = await db.collection("student").find().toArray()
console.log(results)
}
run();

Electron store my app datas in 'userData' path

I'm building and trying do deploying a packaged electron app. FOr the packaging i used
electron-packager
electron-installer-debian
electron-installer-dmg
electron-winstaller
and I'm facing a little issue where I have to store tha appa datas somewhere in my user computer.
I saw that the good practice is to use the the folder in the path that is returned by the electron method app.getPath('userData').
from the docs
It is The directory for storing the app's configuration files, which by default it is the appData directory appended with the app name.
%APPDATA% on Windows
$XDG_CONFIG_HOME or ~/.config on Linux
~/Library/Application Support on macOS
By my tests sometimes this folder is not created automatically when the app is installed and other times yes and I'm wondering if i should create it or not.
Right now i'm quitting the app if this folder isn't present in the pc with the following code
var DatasPath = app.getPath('userData')
if (!fs.existsSync(DatasPath)){
process.exit()
}
So the question is
should i create the DatasPath folder with fs.mkdirSync(DatasPath); when it is not present or it is 'bad practice to do so', and if I can create the folder i have to warning the user the i have just added that folder?
(Expanding my reply from a "comment" to an "answer")
i don't know if i'm supposed to create it or not so i automatically
make the app quit if there is not that folder
It seems you are taking "userData" too literally? It is not an actual "folder" named "userData – it is a path to where the operating system stores data for that application. Electron currently runs on 3 operating systems and each one does things differently. For our convenience, Electron hides those differences by creating the wrapper method app.getPath(name) so the same code will work on each OS.
Try this: put the line below in your main.js script:
console.log(app.getPath('userData'));
/Users/*********/Library/Application Support/MyCoolApp
(the "*********" will be your user account name.)
UPDATED:
Run the code below in main.js and then look in the folder specified by the "userData" path
const fs = require("fs");
const path = require('path');
var datasPath = app.getPath('userData')
var data = "I am the cheese"
var filePath = path.join(datasPath, "savedData.txt")
fs.writeFileSync(filePath, data)
At pathConfig.js
function getAppDataPath() {
switch (process.platform) {
case "darwin": {
return path.join(process.env.HOME, "Library", "Application Support", "myApp");
}
case "win32": {
return path.join(process.env.APPDATA, "myApp");
}
case "linux": {
return path.join(process.env.HOME, ".myApp");
}
default: {
console.log("Unsupported platform!");
process.exit(1);
}
}
}
const appPath = __dirname;
const appDataPath =
!process.env.NODE_ENV || process.env.NODE_ENV === "production"
? getAppDataPath() // Live Mode
: path.join(appPath, "AppData"); // Dev Mode
if (!fs.existsSync(appDataPath)) {
// If the AppData dir doesn't exist at expected Path. Then Create
// Maybe the case when the user runs the app first.
fs.mkdirSync(appDataPath);
}
In each operating system the appData folder has a different path and the perfect way of getting this path is by calling app.getPath('userData') in the main process.
But there is a package that can handle this for you, it stores data in a JSON file and update it in every change.
In my opinion this package is much better than handling everything by your self.
Read more :
https://www.npmjs.com/package/electron-data-holder

How does module.exports = mongoose; work when requiring "./database"?

I'm a MERN stack beginner. I came across this snippet of code from a basic CRUD and I know that it works, but I don't get how.
//in server.js
const database = require('./database');
//in database.js
const mongoose = require('mongoose'); //importing mongoose
mongoose.connect('mongodb://localhost/monguse', {useNewUrlParser:true}) //connected to db
.then((db)=>{console.log('Database connected')}) //message if ok
.catch((err) =>{console.log(`Database connection error: ${err}`)}); //catching errors
module.exports = mongoose;
I understand what is going on in database.js (It is my own version), but why does it work without using any method in server.js? It appears to make the connection only from using the "require" function. then in my routes there is no mention of that again; just using mongoose models in the requests.
Thanks!
In database.js you create an instance of the database and export it by name mongoose, and in server.js you are importing that instance of the mongoDB by name database.

Simple and elegant way to override local file If exists?

Looking for elegant and simple solution to have "local configuration override" files.
The idea is to be able to have local configuration that will not ask to be added to git repository every time.
For that I need to include local.config.js if it exists.
I have global app configuration in config.js with configuration like
export const config = {
API_URL="https://some.host",
}
and config.local.js
export const config = {
API_URL="https://other.address",
}
there's .gitignore:
config.local.js
Difficulty:
I do not want to add a node module to project just for this one thing. I believe there should be an elegant way to do this in one or few lines, but have not found any so far.
Things that I tried:
1.
try {
const {
apiUrl: API_URL,
} = require('./config.local.js');
config. API_URL =apiUrl;
} catch (e) {
}
require does not work inside try{} block.
2.
const requireCustomFile = require.context('./', false, /config.local.js$/);
requireCustomFile.keys().forEach(fileName => {
requireCustomFile(fileName);
});
does not work.
3.
export const config = require('./config.local.js') || {default:'config = {...}'}
does not work.
4.
Using .env and settings environment variable: I need to override whole array of configuration values. Not one by one.
This solution uses process.argv. It is native to node as documented here and does not use .env
It inspects the command values used to start the app. Since these should be different between your local and production environments, it's an easy way to switch with no additional modules required.
command prompt to start your node app:
(this might also be in package.json and incurred via npm start if you're using that approach.)
$ node index.js local
index.js of your node app:
var express = require('express');
var config = require('./config');
if (process.argv[2] === 'local') {
// the 3rd argument provided at startup (2nd index) was 'local', so here we are!
config = require('./config_local');
}
var app = express();
// rest of owl…

Categories