Node.js Connection Examples¶
The ioredis package is the recommended client for Redis when using Node.js.
Connecting with SSL¶
Connecting to your instance via SSL requires using a certificate authority. See documentation for certificates and fingerprints for more details.
var Redis = require('ioredis');
var fs = require('fs');
var ping = function(e) {
var result = client.ping()
.then(function(e) {
console.log(client);
console.log('Connected!');
})
.catch(function(e) {
console.log('Error:', e);
})
.finally(function() {
client.quit();
});
};
try {
var client = new Redis({
host: '#####.publb.rackspaceclouddb.com',
port: 1234,
password: 'YOUR_PASSWORD',
tls: {
ca: fs.readFileSync('LOCAL/PATH/TO/rackspace-ca-2016.pem')
}
});
ping();
}
catch (e) {
console.log('Error: ', e);
}
Connecting without SSL¶
var Redis = require('ioredis');
var fs = require('fs');
var ping = function(e) {
var result = client.ping()
.then(function(e) {
console.log(client);
console.log('Connected!');
})
.catch(function(e) {
console.log('Error:', e);
})
.finally(function() {
client.quit();
});
};
try {
var client = new Redis({
host: '#####.publb.rackspaceclouddb.com',
port: 1234,
password: 'YOUR_PASSWORD'
});
ping();
}
catch (e) {
console.log('Error: ', e);
}
Creating, Reading, Updating and Deleting Records¶
var Redis = require('ioredis');
var fs = require('fs');
try {
var client = new Redis({
host: '#####.publb.rackspaceclouddb.com',
port: 1234,
password: 'YOUR_PASSWORD',
tls: {
ca: fs.readFileSync('LOCAL/PATH/TO/rackspace-ca-2016.pem')
}
});
client.set('best_car_ever', 'Tesla Model S', function (err, result) {
console.log('Set Record: ', result);
});
client.get('best_car_ever', function (err, result) {
console.log('Get Record:', result);
});
client.del('best_car_ever', function (err, result) {
console.log('Delete Record:', result);
});
client.get('best_car_ever', function (err, result) {
console.log('Get Deleted Record:', result);
});
client.quit();
}
catch (e) {
console.log('Error: ', e);
}
Output from above:
Set Record: OK
Get Record: Tesla Model S
Delete Record: 1
Get Deleted Record: null
More Information¶
If you need additional help with ioredis, here are some useful links:
As always, if you have any questions, please don’t hesitate to reach out to our support team!