If you are a developer on a Windows machine and you want to access a Redis Server while you build your application, you have several options; one of them is to use the Redis port on Windows project by MSOpenTechdownload the latest binaries and have your Redis Server running on Windows. Another option is to have a Linux VM running on your machine and connect to it whenever you need it.

Now you have one more option, with the Windows 10 Anniversary update and Bash on Windows. You can have it installed on Bash on Ubuntu on Windows and access it as if it were installed locally on your machine.

[box type=”note” width=”100%” ]If you haven’t setup Bash on Windows 10 you can read about it here.[/box]

Install Redis on Bash on Windows

Open the Start Menu and search for “Bash”:

bash-on-windows

Then install the Redis Server using apt-get:

sudo apt-get install redis-server

After installing it, hit `redis-server` and Redis Server will start:

redis-server-on-bash-windows

By default, the Redis Server accepts connections in port `6379`, so, in order to connect from your Windows machine, you can gain access using`localhost:6379` url.

Connecting using Redis Desktop Manager

redis-desktop-manager-bash-windows

NodeJS app connecting to Redis Server

If you want to connect to Redis with NodeJS you need to start Redis Server as a service, otherwise you will get an error like the following:

Error: Redis connection to 127.0.0.1:6379 failed – connect ECONNREFUSED 127.0.0.1:6379
at Object.exports._errnoException (util.js:1012:11)
at exports._exceptionWithHostPort (util.js:1035:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1080:14)

In order to do so, you need to execute the following command on Bash:

$ sudo service redis-server start

Then you need to create a very simple node app so that you can properly connect to Redis Server.

Step 1. Initialize node app

Start a new project by creating a folder redis-test and in command prompt execute:

npm init

to initialize node project, and then:

npm install redis --save

to install the Redis library, and update package.json and the app’s dependencies.

Step 2. Code snippet to test connection

Create a file app.js with the following code to test the Redis connection:

// app.js
var redis = require('redis');
var client = redis.createClient();
 
client.on('connect', function() {
    console.log('connected');
});
client.set('framework', 'AngularJS');

Run your app with the following command:

node app.js

The response will be connected and there will be a “framework” key with value “AngularJS” in your Redis Server.

redis-connection

Categorized in: