node中的数据持久化

这篇文章讲解的是 node 而不是浏览器,浏览器有 storage 和 cookie,但是 node 这些东西都没有。
node 中实现数据的持久化的多种方法如下:
1、文件系统 fs
2、数据库
•关系型数据库 mysql•文档型数据库 mongodb•键值的对数据库 redis
文件系统就是通过 fs 模块进行操作,这种方式简单便捷,模块直接就可以使用无需安装。
//实现一个文件系统读取数据库const fs = require("fs");function get(key) {fs.readFile("./db.json", (err, data) => {const json = JSON.parse(data);console.log(json[key]);});}function set(key, value) {//可能是空文件, 则设置为空对象const json = data ? JSOJN.parse(data) : [];json[key] = value; //设置值fs.writeFile("./db.json", JSON.stringify(json), (err) => {if (err) {console.log(err);}console.log("写入成功");});}
关系型数据库 mysql 模块的基本使用,需要先 install 安装 mysql 模块。
//mysql.jsconst mysql = require("mysql");//链接配置const cfg = {host: "localhost",user: "root",password: "example",database: "kkk", //确保数据库存在};//创建连接对象const conn = mysql.createConnection(cfg);//链接conn.connect((err) => {if (err) {throw err;} else {console.log("connect success");}});//查询 conn.query()//创建表const CREATE_SQL = `CREATE TABLE IF NOT EXISTS TEST(id INT NULL AUTO_INCREMENT,message VARCHAR(45) NULL,PRIMARY KEY (id))`;const INSERT_SQL = `INSERT INTO test(message) VALUES(?)`;const SELECT_SQL = `SELECT * FROM test`;conn.query(CREATE_SQL, (err) => {if (err) {throw err;}//conn.query(INSERT_SQL, "hellow,world", (err, result) => {if (err) {throw err;}console.log(result);conn.query(SELECT_SQL, (err, result) => {console.log(result);conn.end(); //若query语句有嵌套,则end需要在此执行});});});
基于 Promise 的 ORM,支持多种数据库、事物、关联等。sequelize 模块的基本使用,这种方式需要安装 sequelize 模块。
(async () => {const Sequelize = require("sequelize");// 建⽴连接const sequelize = new Sequelize("kaikeba", "root", "example", {host: "localhost",dialect: "mysql",operatorsAliases: false,});// 定义模型const Fruit = sequelize.define("Fruit", {name: { type: Sequelize.STRING(20), allowNull: false },price: { type: Sequelize.FLOAT, allowNull: false },stock: { type: Sequelize.INTEGER, defaultValue: 0 },});let ret = await Fruit.sync();console.log("sync", ret);ret = await Fruit.create({name: "⾹蕉",price: 3.5,});console.log("create", ret);ret = await Fruit.findAll();await Fruit.update({ price: 4 }, { where: { name: "⾹蕉" } });console.log("findAll", JSON.stringify(ret));const Op = Sequelize.Op;ret = await Fruit.findAll({// where: { price: { [Op.lt]:4 }, stock: { [Op.gte]: 100 } }where: { price: { [Op.lt]: 4, [Op.gt]: 2 } },});console.log("findAll", JSON.stringify(ret, "", "\t"));})();
Redis 是一种支持 key-value 等多种数据结构的存储系统。可用于缓存,事件发布或订阅,高速队列等场景。
评论
