How to include given mode in index.js - node.js

I have this given module in config.js. I want to include this is my index.js. I tried multiple ways but config variable is always undefined.
I tried like this.
const config = require('./config') //undefined
const config = require('./config')("dev") //error
const config = require('./config')["dev"] // error
const config = require('./config').get("dev")
Here is how i run it
// my command.
npm run start:dev
"scripts": {
"start:prod": "set NODE_ENV=prod pm2 start index.js --watch",
"start:dev": "set NODE_ENV=dev && node index.js"
},
Here is module
let env = process.env.NODE_ENV;
require('dotenv').config();
const dev = {
app: {
port: parseInt(process.env.DEV_APP_PORT) || 3000
},
db: {
host: process.env.DEV_DB_HOST || 'localhost',
port: parseInt(process.env.DEV_DB_PORT) || 27017,
name: process.env.DEV_DB_NAME || 'myDB',
},
imagePath: "./profileImages/",
LogFillePath: "logs/combined.log",
ErrorFilePaht: "logs/error.log",
JwtSecret: process.env.JWT_SECRET
};
const prod = {
app: {
port: parseInt(process.env.PROD_APP_PORT) || 9000
},
db: {
host: process.env.PROD_DB_HOST || 'localhost',
port: parseInt(process.env.PROD_DB_PORT) || 27017,
name: process.env.PROD_DB_NAME || 'myDB'
},
imagePath: "./profileImages/",
LogFillePath: "logs/combined.log",
ErrorFilePaht: "logs/error.log",
JwtSecret: process.env.JWT_SECRET
};
const config = {
dev,
prod
};
module.exports = config[env];
I have this given module in config.js. I want to include this is my index.js. I tried multiple ways but config variable is always undefined.
I tried like this.

Try something like this for your config.js:
require("dotenv").config();
const dev = {
// ...
};
const prod = {
// ...
};
const configs = {
dev,
prod,
};
const config = configs[process.env.NODE_ENV];
if (!config) throw new Error("No valid configuration found, ensure your NODE_ENV is properly set");
module.exports = config;
Then you can simply
const config = require('./config');

Related

Nuxt JS SSL Server Installation Problem on MacOS

Hello friends.
I need to continue my Nuxt JS work with SSL. However, after installation, I am getting the following error. I know the problem is because Node JS doesn't recognize the word "IMPORT". But I don't know how to solve the problem. Because I use Components as IMPORT all over the project. What is your suggestion?
Thank you very much in advance. 👋
package.json
"dev": "node server.js",
"nuxt": "^2.15.7",
"express": "^4.17.1"
ERROR IMAGE
error
SyntaxError: Cannot use import statement outside a module at compileFunction (<anonymous>)
nuxt.config.js
import axiosModule from './modules/axiosModule'
import momentModule from './modules/momentModule'
export default {
server: {
host: '0.0.0.0',
port: 3000,
},
......
server.js
const { Nuxt, Builder } = require('nuxt')
const expressServer = require('express')()
const thisHttp = require('http')
const thisHttps = require('https')
const thisFs = require('fs-extra')
const isProd = (process.env.NODE_ENV === 'production')
const isPort = 3000
let thisServer
if (isProd) {
const pKey = thisFs.readFileSync('./key.pem')
const pCert = thisFs.readFileSync('./cert.pem')
const httpsOptions = { key: pKey, cert: pCert }
thisServer = thisHttps.createServer(httpsOptions, expressServer)
} else {
thisServer = thisHttp.createServer(expressServer)
}
const nuxtConfig = require('./nuxt.config')
nuxtConfig.dev = !isProd
const nuxtServer = new Nuxt(nuxtConfig)
expressServer.use(nuxtServer.render)
const listen = () => { thisServer.listen(isPort, 'localhost') }
if (nuxtConfig.dev) {
new Builder(nuxtServer).build().then(listen()).catch(error => { console.log(error); process.exit(1) })
} else {
listen()
}
I fixed the situation manually. I did REQUIRE instead of IMPORT in Nuxt Config and used module.exports instead of Export Default. Even though I'm currently logging in via HTTPS, it's crossed out by Google Chrome.

How to use NODE_ENV to choose which database is connected?

I am attempting to use the value for NODE_ENV in my node.js server to connect to a different database when running my tests. How can I get the correct values for NODE_ENV i.e 'development', 'test', 'production' to make what I've got below work?
import pg from "pg";
import dotenv from "dotenv";
dotenv.config();
const Pool = pg.Pool;
const enviroment = () => {
if (process.env.NODE_ENV === "test") {
return process.env.TEST_DATABASE;
} else {
return process.env.DEVELOPMENT_DATABASE;
}
};
const pool = new Pool({
password: process.env.PASSWORD,
host: process.env.HOST,
port: process.env.PORT,
database: enviroment()
});
export default pool;
.env includes
NODE_ENV=development
NODE_ENV=production
NODE_ENV=test
Thanks.
Seems your code is fine. I think you made a typo in your .env file.
Here is a sample for your .env:
NODE_ENV=test
TEST_DATABASE=mongodb://localhost:27017
DEVELOPMENT_DATABASE=mongodb://localhost:27018
PASSWORD=abcxyz
HOST=localhost
PORT=8000
Don't use NODE_ENV="test", spaces, or anything like this.

node js express server postgres 500 internal server error

My api has stopped working, previously it worked fine and as far as i am aware I have changed nothing. When i tested my endpoint i received an internal server error.
Here is a link to my hosted api https://frozen-scrubland-34339.herokuapp.com/api
I have just checked some of my other apis and none are working either, same message. it appears my code isnt the issue but postgres itself?
Any help on what to do would be appreciated
When i tried to npm run prod to re-push it to heroku i received: 'Error: The server does not support SSL connections'
Again this was never an issue previously when it worked.
I imagine i have changed something with heroku itself by accident?
app.js
const express = require("express");
const app = express();
const apiRouter = require("./routers/api-router");
const cors = require("cors");
const {
handle404s,
handlePSQLErrors,
handleCustomError,
} = require("./controllers/errorHandling");
app.use(cors());
app.use(express.json());
app.use("/api", apiRouter);
app.use("*", handle404s);
app.use(handlePSQLErrors);
app.use(handleCustomError);
module.exports = app;
connection.js
const { DB_URL } = process.env;
const ENV = process.env.NODE_ENV || "development";
const baseConfig = {
client: "pg",
migrations: {
directory: "./db/migrations",
},
seeds: {
directory: "./db/seeds",
},
};
const customConfigs = {
development: { connection: { database: "away_days" } },
test: { connection: { database: "away_days_test" } },
production: {
connection: {
connectionString: DB_URL,
ssl: {
rejectUnauthorized: false,
},
},
},
};
module.exports = { ...baseConfig, ...customConfigs[ENV] };

Why heroku fails to bind to $PORT when I use webpack.definePlugin with parsed dotenv

I am trying to deploy a node.js app to heroku which is bundled with webpack. Due to heroku logs I face with the following error:
Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch
App does not use a fixed port to listen on.
app.listen(process.env.PORT || 3000, () => {
log(`App is running: 🌎 http://localhost:${process.env.PORT || 3000}`, 'info');
});
I have also tried to use '0.0.0.0':
app.listen(process.env.PORT || 3000, '0.0.0.0' () => {
log(`App is running: 🌎 http://localhost:${process.env.PORT || 3000}`, 'info');
});
I noticed that if I use webpack.definePlugin with parsed dotenv I face with this issue, but if I don't use it all is fine.
I have the following .env file that I use for webpack.definePlugin:
const fs = require('fs');
const paths = require('./paths');
const defaultVars = {
NODE_ENV: process.env.NODE_ENV || 'development'
};
const stringifyEnv = (obj) => ({
'process.env': Object.keys(obj).reduce((env, key) => {
env[key] = JSON.stringify(obj[key]);
return env;
}, {})
});
module.exports = () => {
if (fs.existsSync(paths.dotenv)) {
const dotenv = require('dotenv').config();
const env = { ...dotenv.parsed, ...defaultVars };
return stringifyEnv(env);
}
return stringifyEnv(defaultVars);
};
Tried to list dotenv in devDependencies.
Could you please tell what can be wrong?
I managed to make it working by passing a port explicitly.
Procfile
web: node build/server/server.js --port $PORT
server.js
const argv = require('yargs').argv;
...
app.listen(argv.port || process.env.PORT || 3000, () => {
log(`App is running: 🌎 http://localhost:${argv.port || process.env.PORT || 3000}`, 'info');
});
But it still does not answer the question above.

How to pass process.env.NODE_ENV from Gulp to Webpack?

I have a gulpfile, where I create a webpackDevServer to live-update my js code. I set a process.env.NODE_ENV variable in gulpfile, but for some reason webpack doesn't see it - it is undefined.
Here's the relevant piece of my gulpfile.js:
gulp.task("watch", ["_set-env:dev"], function() {
// modify default webpack configuration for Development Server
var webpackDevConfig = Object.create(webpackConfig);
webpackDevConfig.devtool = "eval";
webpackDevConfig.debug = "true";
new webpackDevServer(webpack(webpackDevConfig), {
proxy: {
"/api/*": {target: "http://localhost:8000", secure: false},
"/static/*": {target: "http://localhost:8000", secure: false},
"/media/*": {target: "http://localhost:8000", secure: false}
}
}).listen(8001, "localhost", function (err) {
if (err) throw new gutil.PluginError("webpack-dev-server", err);
gutil.log("[webpack-dev-server]", "http://localhost:8001" + webpackDevConfig.output.publicPath);
});
});
gulp.task("_set-env:dev", function() {
gutil.log("set-env", "ENV => development");
genv({
vars: {
NODE_ENV: "development"
}
});
});
Then in webpack I check its value and it is undefined:
const webpack = require("webpack");
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
...
const environmentsFile = path.join(__dirname, "/environments.json");
const nodeModulesPath = path.join(__dirname, "/node_modules");
const bowerComponentsPath = path.join(__dirname, "/bower_components");
console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
console.log(process.env.NODE_ENV);
const webpackConfig = {
entry: {
app: ["app.js"]
},
And on the console I see:
$ gulp watch
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
undefined
[22:28:34] Using gulpfile ~/Documents/frontend/gulpfile.js
[22:28:34] Starting '_set-env:dev'...
[22:28:34] set-env ENV => development
[22:28:34] Finished '_set-env:dev' after 7.63 ms
[22:28:34] Starting 'watch'...
You probably have something like this close to the top of your gulpfile:
var webpackConfig = require('./webpack.config.js');
That means your webpack configuration is evaluated before the _set-env:dev task even runs. Remember: your gulpfile only defines tasks. The tasks themselves aren't run until after the entire gulpfile has been evaluated.
You need to defer requiring your webpack configuration until after the _set-env:dev task has run by deleting the line at the top of your gulpfile and putting the require() directly into your watch task:
gulp.task("watch", ["_set-env:dev"], function() {
// modify default webpack configuration for Development Server
var webpackDevConfig = Object.create(require('./webpack.config.js'));

Resources