The front-end can implement data persistence by manipulating files or databases. Here are a few ways to do this. If you have any mistakes or questions, please correct them.

1. Data persistence mode

There are several ways to persist data:

  • The file system

  • The database

  1. Relational database -mysql
  2. Key value pair database – Redis
  3. Document database -mongodb

2. File system database

Use the readFile() and writeFile() methods of fs module to implement asynchronous file read and write, as well as the synchronous readFileSync() and writeFileSync(), the synchronous readFileSync program will wait for IO operation, during the waiting time, Unable to respond to any other events and unable to define a callback function. Therefore, asynchronous methods are often used.

// test.js 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 = JSON.parse(data); json[key] = value; // Write to fs.writefile ('./db.json', json.stringify (json), Err => {if(err){console.log(err)}else{console.log(' write successfully ')}})} // command line const readline = require('readline'); const rl = readline.createInterface({ input: process.stdin, output: process.stdout }) rl.on('line', 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(); } }) rl.on('close', () => { process.exit(0); })Copy the code

The running results are as follows:

Nodetest. js set test {name:11} Get test {name:11}Copy the code

2. Relational database mysql

Install the mysql2 package first:

yarn add mysql2
Copy the code

Example code is as follows:

(async () => { const mysql = require('mysql2/promise'); Const connection = await mysql.createconnection ({host: 'localhost', user: 'root', password: '123456', // The password must be a string. Database: 'test'}); Let result = await connection.execute('CREATE TABLE IF NOT EXISTS user (id INT NOT NULL AUTO_INCREMENT,name VARCHAR(45) NULL,PRIMARY KEY (ID))') console.log(result); // Add result = await connection.execute('INSERT INTO user(name) VALUES(?) ', ['Lucy']); Console. log(' added successfully ', result); Result = await connection.execute('DELETE FROM user WHERE name=? ', ['Lucy']); Console. log(' delete succeeded ', result); }) ()Copy the code

Generally, a database connection pool is established in a real project, and the number of database connections is reduced by reusing previous connections, thus reducing the pressure on the database.

(async () => { const mysql = require('mysql2/promise'); const pool = mysql.createPool({ host: 'localhost', user: 'root', password: '123456', database: 'test' }); Let result = await pool.execute('CREATE TABLE IF NOT EXISTS user (id INT NOT NULL AUTO_INCREMENT,name VARCHAR(45) NULL,PRIMARY KEY (id))') console.log(result); // Add result = await pool.execute('INSERT INTO user(name) VALUES(?) ', ['Lily']); Console. log(' added successfully ', result); }) ()Copy the code

3. ORM-Sequelize

ORM(Object Relation Mapping) based on Promise is a kind of database middleware, supporting a variety of databases, transactions, association and so on. You can operate the database by manipulating objects without writing native SQL statements. However, for complex datatype queries, the capabilities of the middleware may be somewhat limited.

First install the dependency package Sequelize.

yarn add Sequelize
Copy the code

Example code is as follows:

(async () => { const Sequelize = require('sequelize'); // Parameters are 'database', 'username', 'password' const sequelize = new sequelize ('test', 'root', '123456', {host: 'localhost', dialect: 'mysql' /* one of 'mysql' | 'mariadb' | 'postgres' | 'mssql' */ }); // Define model const User = sequelize.define('User', {name: {type: sequelize.string (20), allowNull: false}, role: {type: Sequelize.integer, defaultValue: 0}}) let ret = await user.sync (); Update ({role: 2},{where: {name: {name: {role: 1}); Const Op = sequelize.op; const Op = sequelize.op; ret = await User.findAll({ where: { role: { [Op.eq]: 2 } } }) console.log(ret); / / delete data ret = await User. Destroy ({where: {role: {[Op. Eq] : 3}}})}) ()Copy the code

If you need to set UUID- primary key:

id: {
    type: Sequelize.DataTypes.UUID,
    defaultValue: Sequelize.DataTypes.UUIDV1,
    primaryKey: true
}
Copy the code

Refer to the official documentation for more usage:

Sequelize.org/master/inde…

www.npmjs.com/package/seq…

The above is from the summary of online learning materials.