node-redis基本操作

//npm install redis
var redis = require("redis"),
  client = redis.createClient();

client.set("stringkey", "v1", redis.print);
client.get('stringkey', function (err, data) {
  console.log(data);
  client.quit();
})


// client.hset("hashkey", "hashtest 1", "some value", redis.print);
// client.hset(["hashkey", "k1", "v1", "k2", "v2"], redis.print);
// client.hkeys("hashkey", function (err, replies) {
//     console.log(replies.length + " replies:");
//     replies.forEach(function (reply, i) {
//         console.log("    " + i + ": " + reply);
//     });
//     client.quit();
// });
// client.hget("hashkey", "k1", function (err, data) {
//   console.log(data);
//   client.quit();
// });
// client.hgetall("hashkey", function (err, data) {
//   console.log(data);
//   client.quit();
// })


//client.lpush("listkey", ["s1", "s2", "s3", "s4"], redis.print);
// client.lrange("listkey", 0, 10 ,function (err, data){
//   console.log(data);
//   client.quit();
// })


// client.sadd("setkey", ["s1", "s2", "s3"], redis.print);
// client.smembers("setkey", function (err ,datas){
//   console.log(datas);
//   client.quit();
// })


// client.zadd("zsetkey", [1, "z1", 2, "z2", 3, "z3"], redis.print);
// client.ZRANGEBYSCORE("zsetkey", 0, 100, function (err, datas) {
//   console.log(datas);
//   client.quit();
// })


// 可以监听很多事件 ready connect reconnecting error end......
// 所有事件可以去官方文档上看下
//https://github.com/NodeRedis/node_redis
// client.on("error", function (err) {
//   console.log("Error " + err);
// });

// 记得关闭,用完记得关闭,记得关闭 
// client.quit();
// 不会用的都记得删除
// client.DEL("zsetkey",redis.print);

//这里有部分redis的注意事项
//https://www.cnblogs.com/chang290/p/3601674.html
//想看完整版的就直接看官方的
//https://github.com/NodeRedis/node_redis



//补充


//1.Native Promises
// //v8以上可以这么用
// const {promisify} = require('util');
// const getAsync = promisify(client.get).bind(client);
// // We expect a value 'foo': 'bar' to be present
// // So instead of writing client.get('foo', cb); you have to write:
// return getAsync('foo').then(function(res) {
//   console.log(res); // => 'bar'
// });
// async myFunc() {
//   const res = await getAsync('foo');
//   console.log(res);
// }





// //2.Bluebird Promises
// const redis = require('redis');
// bluebird.promisifyAll(redis);

// // We expect a value 'foo': 'bar' to be present
// // So instead of writing client.get('foo', cb); you have to write:
// return client.getAsync('foo').then(function(res) {
//     console.log(res); // => 'bar'
// });

// // Using multi with promises looks like:

// return client.multi().get('foo').execAsync().then(function(res) {
//     console.log(res); // => 'bar'
// });





原文地址:https://www.cnblogs.com/csnd/p/12061842.html