node中的數(shù)據(jù)持久化

這篇文章講解的是 node 而不是瀏覽器,瀏覽器有 storage 和 cookie,但是 node 這些東西都沒(méi)有。
node 中實(shí)現(xiàn)數(shù)據(jù)的持久化的多種方法如下:
1、文件系統(tǒng) fs
2、數(shù)據(jù)庫(kù)
?關(guān)系型數(shù)據(jù)庫(kù) mysql?文檔型數(shù)據(jù)庫(kù) mongodb?鍵值的對(duì)數(shù)據(jù)庫(kù) redis
文件系統(tǒng)就是通過(guò) fs 模塊進(jìn)行操作,這種方式簡(jiǎn)單便捷,模塊直接就可以使用無(wú)需安裝。
//實(shí)現(xiàn)一個(gè)文件系統(tǒng)讀取數(shù)據(jù)庫(kù)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) {//可能是空文件, 則設(shè)置為空對(duì)象const json = data ? JSOJN.parse(data) : [];json[key] = value; //設(shè)置值fs.writeFile("./db.json", JSON.stringify(json), (err) => {if (err) {console.log(err);}console.log("寫入成功");});}
關(guān)系型數(shù)據(jù)庫(kù) mysql 模塊的基本使用,需要先 install 安裝 mysql 模塊。
//mysql.jsconst mysql = require("mysql");//鏈接配置const cfg = {host: "localhost",user: "root",password: "example",database: "kkk", //確保數(shù)據(jù)庫(kù)存在};//創(chuàng)建連接對(duì)象const conn = mysql.createConnection(cfg);//鏈接conn.connect((err) => {if (err) {throw err;} else {console.log("connect success");}});//查詢 conn.query()//創(chuàng)建表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語(yǔ)句有嵌套,則end需要在此執(zhí)行});});});
基于 Promise 的 ORM,支持多種數(shù)據(jù)庫(kù)、事物、關(guān)聯(lián)等。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 等多種數(shù)據(jù)結(jié)構(gòu)的存儲(chǔ)系統(tǒng)。可用于緩存,事件發(fā)布或訂閱,高速隊(duì)列等場(chǎng)景。
評(píng)論
圖片
表情
