const express = require('express') const bodyParser = require('body-parser') const repo = require('./repository') const app = express() const port = process.env.PORT || 3000 // The body-parser middleware // to parse form data app.use(bodyParser.urlencoded({extended : true})) // Get route to display HTML form app.get('/signup', (req, res) => { res.send(`
placeholder='Email' for='email'>
placeholder='Password' for='password'>
`); }) // Post route to handle form submission // logic and add data to the database app.post('/signup', async (req, res) => { const {email, password} = req.body const addedRecord = await repo.createNewRecord({email, password}) console.log(`Added Record : ${JSON.stringify(addedRecord, null, 4)}`) res.send("Information added to the" + " database successfully.") }) // Server setup app.listen(port, () => { console.log(`Server start on port ${port}`) })
文件名:repository.js
// Importing node.js file system module const fs = require('fs') class Repository { constructor(filename) { // Filename where datas are going to store if (!filename) { throw new Error( 'Filename is required to create a datastore!') } this.filename = filename try { fs.accessSync(this.filename) } catch (err) { // If file not exist // it is created with empty array fs.writeFileSync(this.filename, '[]') } } // Logic to add data async createNewRecord(attributes) { // Read filecontents of the datastore const jsOnRecords= await fs.promises.readFile(this.filename,{ encoding : 'utf8' }) // Parsing JSON records in Javascript // object type records const objRecord = JSON.parse(jsonRecords) // Adding new record objRecord.push(attributes) // Writing all records back to the file await fs.promises.writeFile( this.filename, JSON.stringify(objRecord, null, 2) ) return attributes; } } // The 'datastore.json' file created at // runtime and all the information // provided via signup form store in // this file in JSON formet. module.exports = new Repository('datastore.json')
本文深入探讨了NoSQL数据库的四大主要类型:键值对存储、文档存储、列式存储和图数据库。NoSQL(Not Only SQL)是指一系列非关系型数据库系统,它们不依赖于固定模式的数据存储方式,能够灵活处理大规模、高并发的数据需求。键值对存储适用于简单的数据结构;文档存储支持复杂的数据对象;列式存储优化了大数据量的读写性能;而图数据库则擅长处理复杂的关系网络。每种类型的NoSQL数据库都有其独特的优势和应用场景,本文将详细分析它们的特点及应用实例。 ...
[详细]