Using Redis under node. js, First:
1, there is a server with Redis installed, of course, installed in this machine is also OK
2, this machine, that is, the client, to install node. js
3, the project to install the Nodejs_redis module
Note that the 3rd, not the local installation on the line, but to say, to install (reference) in the project.
method is, DOS window, under project directory, enter
NPM Install Redis
This will download a copy of the Nodejs_redis and put it in the current directory. Look, there's one more folder: Node_modules\redis
Write the following code to save to the current directory \hello.js
var Redis = require ("Redis"),//summon redis/* to connect to the Redis database, createclient (port,host,options); If Redis is on this machine, the port is the default, Direct Write CreateClient () can redis.createclient () = Redis.createclient (6379, ' 127.0.0.1 ', {}) */client = Redis.createclient ( 6379, ' 192.168.159.128 ', {});//if validation is required, verify//client.auth (password, callback);/If you ' d like to select Database 3, Instead of 0 (default), call//client.select (3, function () {/* ... */});//Error monitoring? Client.on ("Error", function (Err) {Console.log ("error" + Err);}); Client.set ("String Key", "string Val", Redis.print),//set "String Key" "String Val"/*redis.print, callback function, displays the return value of Redis. The result of the previous sentence will return "OK" */client.hset ("Hash Key", "Hashtest 1", "some value", redis.print); Client.hset (["Hash Key", "Hashtest 2" , "Some other value"], redis.print);//traversal hash table "Hash key" Client.hkeys ("hash Key", function (err, replies) {Console.log (rep Lies.length + "replies:"); Replies.foreach (function (reply, i) {Console.log ("" + i + ":" + Reply); }); Client.hget ("Hash Key", "Hashtest 1", RediS.print); /* Two can be disconnected from the Redis connection, end () very rough, no matter 3721, suddenly quit, the above sentence to get the hash table "hash key" of an element value of the expression will have no results returned and quit () is the statement processing finished and then cleanly exit, Sven very */// Client.end (); Client.quit ();});
node. JS Application Redis Database