Set up Knex ORM console with REPL

Sobin Sunny
1 min readAug 30, 2019

--

When I started working with NodeJs ORMs, first I looked for a ORM console to run my Knex Query. Unfortunately I wasn’t able to find one like rails console. For me ORM console is a playground to save my productive time.

1) Setup Knex DB connector

First step is to create a Postgres connection adapter. Let’s create knexConfig.js

Before that set all your environment variables in .env file

2) Setup Initialization file for REPL

Create one repl.js, which should initialize ORM objects.

We can use dotenv file to load the environment variable from .env file. You can set all your global variable to context.

3) Run console

Let’s make this console to handle asynchronous code. To do that we can start repl console with async await support mode.

node --experimental-repl-await repl.js

Now lets try with a simple Knex query in the console.

 await knex(‘employees’);

It will return the employees list.

Now you can run your knex query in console. :)

More fun !!

In addition to this, we can set this console inside your project. Lets do it as a npm command.

add this code into your package.json

console: "NODE_OPTIONS=--experimental-repl-await babel-node -- repl.js"

This code will also help you to run ES6 code into your console. Use babel-node to to compile the repl file.

Enjoy!!

--

--