week5-node-express-knex-pg/README.md
jc user 13e24154be Update README.md
updated the formatting
2024-10-22 10:09:59 +01:00

2.0 KiB

use knex.js with ES6 on Node and work with .env

The below instructions are intended for command line execution while working with node server

install dotenv and knex.js

npm install dotenv --save
npm install knex --save

In the project root directory, create a folder called 'db' and navigate to this 'db' folder:

execute the following command:

npx knex init

A 'knexfile.js' will be created in this directory.

Change the file extension to .cjs

you will need to add the below line in your package.json file:


"type": "module",

create 2 subfolders inside 'db' folder, called "migrations" and "seeds"

data in .env file

This file should be placed in the project root directory


DEV_USER=
DEV_DB=
DEV_PASSWORD=
DEV_HOST=localhost
DEV_PORT=5432

knexfile.cjs configuration

check current working directory

const dir = process.cwd();

check current running environment

const env = process.env.ENVIRONMENT || "";

the database details here

exports.development = {}
exports.production = {}

below instructions are used on a terminal window navigate to 'db' folder

create a migration file type:


knex migrate:make create_XYZ_table --migrations-directory migrations

make sure to rename the file extensions to .cjs

execute migration type:


knex migrate:latest --knexfile knexfile.cjs --migrations-directory migrations

execute rollback type:


knex migrate:rollback --knexfile knexfile.cjs --migrations-directory migrations

Check out the knex documentation

knex URL: https://knexjs.org/guide/migrations.html#migration-cli

create a seed file type:


knex seed:make 01_XYZ_test_data --knexfile knexfile.cjs

make sure to rename the file extensions to .cjs

execute the seed file type:

knex seed:run --knexfile knexfile.cjs

to run the node server

navigate back to the project root directory and type:

ENVIRONMENT=development npm run dev