I want to use different environment variable file for prod environment and non prod environments. Currently I'm maintaining a single file for all environment and going forward each env file content will be get different according the environment. Hence is there a possibility to rename the file according the environment and pass it at run time or define the respective env file at a configuration file (cypress.json)
Sample env file names:
cypress.env.nonprod.json
cypress.env.prod.json
You can add scripts into project.json file:
{
"scripts": {
"setEnvDev": "cp cypress.env.dev.json cypress.env.json",
"setEnvStaging": "cp cypress.env.staging.json cypress.env.json",
"setEnvSproduction": "cp cypress.env.production.json cypress.env.json"
}
}
And run
$ npm run setEnvDev
$ npx cypress run
You can create cypress configuration files in your project root. Like for example if you have three config files:
production.json
staging.json
dev.json
Then depending on what configuration file you want to use, you can directly run the command:
npx cypress run --config-file staging.json
Set up cypress.env.nonprod.json and cypress.env.prod.json for envrionment-specific, and cypress.env.json for common variables.
In cypress/support/index.js add
const env = Cypress.env() // configured env from common cypress.env.json + command line
if (env.nonprod) { // has nonprod environment been set?
const addEnv = require('cypress.env.nonprod.json')
const merged = {...env, ...addEnv}
Cypress.env(merged)
}
if (env.prod) { // has prod environment been set?
const addEnv = require('cypress.env.prod.json')
const merged = {...env, ...addEnv}
Cypress.env(merged)
}
Run from command line (or set up script)
npx cypress run --env nonprod=true
This allows "stacking" where multiple files can be merged
npx cypress run --env nonprod=true,prod=true
Using cypress/plugins.index.js to merge named environment variable file
// plugins/index.js
module.exports = (on, config) => {
if (config.env.environment) {
const envars = require(`cypress.env.${config.env.environment}.json`
config.env = {
...config.env,
...envars
}
}
return config
}
To add cypress.env.nonprod.json to base config (cypress.json)
npx cypress run --env environment=nonprod
Related
Hi i'm trying to run some gulp task on netlify for building Hugo web.
I wonder how to run serial gulp task on netlify,
by the way this is my gulpfile.js
var gulp = require('gulp');
var removeEmptyLines = require('gulp-remove-empty-lines');
var prettify = require('gulp-html-prettify');
var rm = require( 'gulp-rm' );
var minifyInline = require('gulp-minify-inline');
gulp.task('tojson', function () {
gulp.src('public/**/*.html')
.pipe(removeEmptyLines())
.pipe(gulp.dest('public/./'));
});
gulp.task('htmlClean', function () {
gulp.src('public/**/*.html')
.pipe(removeEmptyLines({
removeComments: true
}))
.pipe(gulp.dest('public/./'));
});
gulp.task('templates', function() {
gulp.src('public/**/*.html')
.pipe(prettify({indent_char: ' ', indent_size: 2}))
.pipe(gulp.dest('public/./'))
});
gulp.task('minify-inline', function() {
gulp.src('public/**/*.html')
.pipe(minifyInline())
.pipe(gulp.dest('public/./'))
});
where should i put the command to run all my gulps task in Netlify?
There are two places to setup your build commands in Netlify.
Admin Option
Put your commands in the online admin under the Settings section of your site and go to Build & Deploy (Deploy settings) and change the Build command:
Netlify Config file (netlify.toml) Option
Edit/add a netlify.toml file to the root of your repository and put your build commands into the context you want to target.
netlify.toml
# global context
[build]
publish = "public"
command = "gulp build"
# build a preview (optional)
[context.deploy-preview]
command = "gulp build-preview"
# build a branch with debug (optional)
[context.branch-deploy]
command = "gulp build-debug"
NOTE:
The commands can be any valid command string. Serializing gulp commands would work fine if you do not want to create a gulp sequence to run them. In example, gulp htmlClean && hugo && gulp tojson would be a valid command.
Commands in the netlify.toml will overwrite the site admin command.
You can string your tasks together like this:
add another plugin with NPM:
https://www.npmjs.com/package/run-sequence
var runSequence = require('run-sequence');
gulp.task('default', function (callback) {
runSequence(['tojson', 'htmlClean', 'templates', 'minify-inline'],
callback
)
})
Then run $ gulp
There's a section on run-sequence on this page that will help:
https://css-tricks.com/gulp-for-beginners/
Based on this answer here https://stackoverflow.com/a/22524056/777700 I have set exactly the same configuration options, but it doesn't work.
My (partial) app.js file:
console.log('environment: '+process.env.NODE_ENV);
const config = require('./config/db.json')[process.env.NODE_ENV || "development"];
console.log(config);
My ./config/db.json file:
{
"development":{
"host":"localhost",
"port":"3306",
"username":"root",
"password":"",
"database":"dbname"
},
"production":{
"host":"production-host",
"port":"3306",
"username":"user",
"password":"pwd",
"database":"dbname"
}
}
Console.log outputs:
environment: development
undefined
and app crashes. Any idea why? File is there, if I remove the [...] part of require(), it does print out the db.json file, with it, it prints out undefined.
EDIT
I tried to add console.log(typeof config) just after require() to see what I'm getting and I have noticed that if I require('./config/db.json')[process.env.NODE_ENV] I get undefined, but if I require('./config/db.json')["development"] I get back proper object.
Versions:
nodeJS 6.11.4
express 4.16.2
After more debugging and searching online, I have finally found the solution. The problem is that I'm on Windows machine and I was using npm run dev command while my "dev" command looked like SET NODE_ENV=development && nodemon server.js.
Experienced eye will notice a space before &&, which added a space behind the variable development, so the variable I was comparing against was "development " and not "development" as I was thinking.
So, the original answer from other question does work and it does load proper config!
You should export configuration as a variable:
const config = {
"development":{
"host":"localhost",
"port":"3306",
"username":"root",
"password":"",
"database":"dbname"
},
"production":{
"host":"production-host",
"port":"3306",
"username":"user",
"password":"pwd",
"database":"dbname"
}
};
module.exports = config;
This way it will be found :)
If you want to do it via JSON:
const fs = require('fs')
let localConfig
try {
localConfig = JSON.parse((fs.readFileSync('./config/db.json', 'utf-8'))
} catch (e) {
console.log('Could not parse local config.')
localConfig = false
}
module.exports = localConfig
You could then add logic for production, if there's no local configuration localConfig will return false and you can look for environment variables injected at that point.
Update:
I see that you're giving the production config yourself, in that case you can just access the key you need based on the environment. Just import localConfig and use the keys you need.
Its better to use dotenv package for this
npm i dotenv
Step 1: In package.json add this
"scripts": {
"start": "nodemon app.js",
"dev": "NODE_ENV=dev nodemon app.js"
"prod": "NODE_ENV=prod nodemon app.js"
},
Step 2: Add .env.prod and .env.dev files
.env.dev
PORT=7200
# Set your database/API connection information here
DB_URI=localhost
DB_USERNAME=root
DB_PASSWORD=password
DB_DEFAULT=dbName
Step 3: Add this in config.js
const dotenv = require('dotenv').config({ path: `.env.${process.env.NODE_ENV}` });
const result = dotenv;
if (result.error) {
throw result.error;
}
const { parsed: envs } = result;
// console.log(envs);
module.exports = envs;
Step 4: Use like this when needed
const {
DB_URI, DB_USERNAME, DB_PASSWORD, DB_DEFAULT,
} = require('../config');
Now if u want for development, run
npm run dev
For prod, use
npm run prod
I am using PM2 to manage the execution of a couple of micro-apps on node.
Goal:
However I would like to be able to automatically switch settings and the cwd value based on the environment the app is executing in.
For example: on my local machine CWD should be ~/user/pm2, while on the server it needs to be E:\Programs\PM2.
Is there any way to do this using JSON config options with PM2? Is there a better way to manage the variables for different environments?
you can save a shell script, say pm2_dev.sh containing the cd command as first line.
#!/bin/bash
cd /foo/bar
pm2-dev run my-app.js
OR you can add input to your script:
# pm2_dev.sh ~/user/pm2
file should be:
#!/bin/bash
cd $1
pm2-dev run my-app.js
If you do not want to change environment by shell script, you can follow documentation way:
{ "apps" : [{
"script" : "worker.js",
"watch" : true,
"env": {
"NODE_ENV": "development",
},
"env_production" : {
"NODE_ENV": "production"
} },{
"name" : "api-app",
"script" : "api.js",
"instances" : 4,
"exec_mode" : "cluster" }] }
When running your application you should use --env option as it is written here:
--env specify environment to get
specific env variables (for JSON declaration)
Finally you can wrap configuration in a js object that conditionally returns parameters basing on current environment:
module.exports = (function(env){
if( env === 'development' )
returnĀ { folder: '~/user/pm2' };
else if( env === 'production' )
returnĀ { folder: 'E:\Programs\PM2' };
}(process.env.NODE_ENV));
Then you can require the config file and access it being sure that it returns always the correct config.
I've read about Fake json-server and I'd like to watch more than 1 file.
In the instructions it is listed
--watch, -w
Watch file(s)
but I'm not able to make it working if I launch it as
json-server -w one.json two.json more.json
create files as shown below
db.js
var firstRoute = require('./jsonfile1.json');
var secondRoute = require('./jsonfile2.json');
var thirdRoute = require('./jsonfile3.json');
var fourthRoute = require('./jsonfile4.json');
// and so on
module.exports = function() {
return {
firstRoute : firstRoute,
secondRoute : secondRoute,
thirdRoute : thirdRoute,
fourthRoute : fourthRoute
// and so on
}
}
server.js
var jsonServer = require('json-server')
var server = jsonServer.create()
var router = jsonServer.router(require('./db.js')())
var middlewares = jsonServer.defaults()
server.use(middlewares)
server.use(router)
server.listen(3000, function () {
console.log('JSON Server is running')
})
Now go to the directory where you have created both these files and open command line and run the code below
node server.js
That's it now go to the browser and go to localhost:3000 ,You shall see the routes that created for different files,you may use it directly.
You can open multipe port for differents json files with json-server.In my case
I open multiples cmd windows and launch it as.
json-server --watch one.json -p 4000
json-server --watch two.json -p 5000
json-server --watch more.json -p 6000
One for cmd window, this work for me.
It can only watch one file. You have to put the all info you need into the same file. So if you need cars for one call and clients for another, you would add a few objects from each into one file. It's unfortunate, but it's just supposed to be a very simple server.
1 - create database file e.g db.json
{
"products": [
{
"id": 1,
"name": "Caneta BIC Preta",
"price": 2500.5
},
],
"users":[
id:1,
name:"Derson Ussuale,
password: "test"
]
}
2 - In Package.json inside script
"scripts": {
"start": "json-server --watch db.json --port 3001"
},
3 - Finally Run command > npm start
Resources
http://localhost:3001/products
http://localhost:3001/users
Home
http://localhost:3001
You can do that with this things:
Step 1: Install concurrently
npm i concurrently --save-dev
Step 2: Create multiple json file, for an example db-users.json, db-companies.json and so on, and so on
Step 3: Add command line to your package.json scripts, for an example:
servers: "concurrently --kill-others \"json-server --host 0.0.0.0 --watch db-users.json --port 3000\" \"json-server --host 0.0.0.0 --watch db-companies.json --port 3001\""
Step 4: Now you can run npm run servers to run your multiple json file.
After that, you can access your server with: localhost:3000 and localhost:3001 or with your network ip address.
Note: You can add more files and more command into your package.json scripts.
That's it.
As you can watch only one file simulteniously, because it is database, you can first read the database file and then append new data to database JSON:
const mockData = jsf(mockDataSchema);
const dataBaseFilePath = path.resolve(__dirname, {YOUR_DATABASE_FILE});
fs.readFile(dataBaseFilePath, (err, dbData) => {
const json = JSON.parse(dbData);
resultData = JSON.stringify(Object.assign(json, mockData));
fs.writeFile(dataBaseFilePath, resultData, (err) => {
if (err) {
return console.log(err);
}
return console.log('Mock data generated.);
});
});
I am following this guide to generate junit output from my js tests:
https://github.com/sbrandwoo/grunt-qunit-junit
I have installed grunt-qunit-junit into my local test project:
npm install grunt-contrib-qunit --save-dev
And this is my Gruntfile.js:
module.exports = function(grunt) {
"use:strict";
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
qunit_junit: {
options: {
},
all: ["all_tests.html"]
},
})
grunt.loadNpmTasks('grunt-qunit-junit');
};
where all_tests.html is located in the same dir and lists all my *test.js files. But when I run:
user#ubuntu:~/Test$ grunt qunit_junit
Running "qunit_junit" task
>> XML reports will be written to _build/test-reports
Done, without errors.
Why are the tests not executed (the folder _build/test-reports is not created)?
The README states that you should execute both the qunit_junit and qunit tasks: http://github.com/sbrandwoo/grunt-qunit-junit#usage-examples
For example: grunt.registerTask('test', ['qunit_junit', 'qunit']);