node_redis, as you may have guessed, is the Redis client for Node.js. You can install it via npm using the following command.
npm install redis
Once you have installed node_redis module you are good to go. Let’s create a simple file, app.js, and see how to connect with Redis from Node.js.
app.js
var redis = require('redis');
client = redis.createClient(); //creates a new client
By default, redis.createClient() will use 127.0.0.1 and 6379 as the hostname and port respectively. If you have a different host/port you can supply them as following:
var client = redis.createClient(port, host);
Now, you can perform some action once a connection has been established. Basically, you just need to listen for connect events as shown below.
client.on('connect', function() {
console.log('connected');
});
So, the following snippet goes into app.js:
var redis = require('redis');
var client = redis.createClient();
client.on('connect', function() {
console.log('connected');
});
Now, type node app in the terminal to run the app. Make sure your Redis server is up and running before running this snippet.