node持久化的几种方式
- 文件系统 csv Comma-Separated Values 逗号分割 xx;xx json 对象序列化 {aa:'11'} => "{aa:'11'}"
- 数据库
- mysql 关系型
- mongodb 文档型
- redis 键值关系
文件系统
//通过本地json对象序列化存储与读取
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) {
fs.readFile("./db.json", (err, data) => {
// 可能是空文件,则设置为空对象
const json = data ? JSON.parse(data) : {};
json[key] = value; // 设置值
// 重新写入文件
fs.writeFile("./db.json", JSON.stringify(json), err => {
if (err) {
console.log(err);
}
console.log("写入成功!");
});
});
}
// 命令行接口部分
const readline = require("readline");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.on("line", function(input) {
const [op, key, value] = input.split(" ");
if (op === 'get') {
get(key)
} else if (op === 'set') {
set(key, value)
} else if(op === 'quit'){
rl.close();
}else {
console.log('没有该操作');
}
});
rl.on("close", function() {
console.log("程序结束");
process.exit(0);
});
//测试 启动后命令行输入
set aa bb
//写入成功!
get aa
//bb
mysql
//安装
npm i sequelize mysql2 -S
//使用:
(async () => {
const mysql = require('mysql2/promise')
// 连接配置
const cfg = {
host: "localhost",
user: "root",
password: "xxx", // 修改为你的密码
database: "xxxx" // 请确保数据库存在
}
const connection = await mysql.createConnection(cfg)
let ret = await connection.execute(`
CREATE TABLE IF NOT EXISTS test (
id INT NOT NULL AUTO_INCREMENT,
message VARCHAR(45) NULL,
PRIMARY KEY (id))
`)
console.log('create', ret)
ret = await connection.execute(`
INSERT INTO test(message)
VALUES(?)
`, ['ABC'])
console.log('insert:', ret)
ret = await connection.execute(`
SELECT * FROM test
`)
console.log(JSON.stringify(ret[0]))
// console.log(ret[1])
connection.end()
})()
基于Promise的ORM (object relation mapping)对象关系映射 - Sequelize
//安装
npm i sequelize sequelize -S
//使用:
(async () => {
// 1:N关系
const Sequelize = require("sequelize");
// 建立连接
const sequelize = new Sequelize("kaikeba", "root", "xxxx", {
host: "xxxxx",
dialect: "mysql",
});
const Fruit = sequelize.define("fruit", { name: Sequelize.STRING });
const Category = sequelize.define("category", { name: Sequelize.STRING });
Fruit.FruitCategory = Fruit.belongsToMany(Category, {
through: "FruitCategory"
});
// 插入测试数据
sequelize.sync({ force: true }).then(async () => {
await Fruit.create(
{
name: "香蕉",
categories: [{ id: 1, name: "热带" }, { id: 2, name: "温带" }]
},
{
include: [Fruit.FruitCategory]
}
);
// 多对多联合查询
const fruit = await Fruit.findOne({
where: { name: "香蕉" }, // 通过through指定条件、字段等
include: [{ model: Category, through: { attributes: ['id', 'name'] } }]
});
})
})()
常用创建命令
//避免生成多余时间字段
timestamps: false
//解决数据库移植唯一问题
id: {
type: Sequelize.DataTypes.UUID,
defaultValue: Sequelize.DataTypes.UUIDV1,
primaryKey: true
},
一对多 多对一关系
const Sequelize = require('sequelize');
module.exports.initModel = async sequelize => {
// 创建user表
const User = sequelize.define('user', { name: Sequelize.STRING });
// 创建商品表
const Product = sequelize.define('product', { title: Sequelize.STRING });
Product.belongsTo(User); // 1端建立关系
User.hasMany(Product); // N端建立关系
return { User, Product }
}