mini- session是用于node.js的极简版session模块,非持久化。它的数据存储在内存里,因此,如果Web服务器进程重新启动,session将会丢失。所以,这个模块主要针对小网站,并没有太多的数据存储在session中。
安装
在使用 mini-session 之前, 你需要先安装 Cookies 包。
npm install cookies
然后
npm install mini-session
Demo
var http = require("http"); var Cookies = require("Cookies"); var Session = require("mini-session"); http.createServer(function(req, res){ var cookies = new Cookies(req, res); var session = new Session(cookies);//init session with cookies console.log("sessionId = " + session.sessionId); session.set("userId", 123); session.set("userName", "Jhon"); console.log("after set, session data is :"); session.dump(); console.log("session.get(\"userId\") = " + session.get("userId")); session.abandon(); console.log("after abandon, session data is :"); session.dump(); res.writeHead(200, {"Content-Type":"text/html"}); res.end("<h1>session test done!</h1>"); }).listen(8500); console.log("Server started : http://localhost:8500");
****控制台输出:
Server started : http://localhost:8500 sessionId = f4e4f42b130bfb4fb663ee67122c02b8 after set, session data is : { count: 1, f4e4f42b130bfb4fb663ee67122c02b8: { count: 2, userId: 123, userName: 'Jhon' } } session.get("userId") = 123 after abandon, session data is : { count: 0 }