12 October 2019

NodeJS ExpressJS: Database (Lowdb) [EX-06]

Lowdb
Cài đặt module
npm install lowdb --save
Refer: https://github.com/typicode/lowdb

/app.js
app.js
const express = require('express')
const app = express()
const port = 3000

// lowdb module
const low = require('lowdb')
const FileSync = require('lowdb/adapters/FileSync')
const adapter = new FileSync('db.json')
const db = low(adapter)
// Set some defaults (required if your JSON file is empty)
db.defaults({ users: []})
.write()

app.set('view engine', 'pug')
app.set('views', './views');

// https://expressjs.com/en/4x/api.html#req.body
app.use(express.json()) // for parsing application/json
app.use(express.urlencoded({ extended: true })) // for parsing application/x-www-form-urlencoded

// GET method route
app.get('/', function (req, res) {
    res.render('index', {
        title: 'Hey',
        message: "ExpressJS"
    })
})

// GET method route
app.get('/users', function (req, res) {
    res.render('users/index', {
        users: db.get('users').value()
    })
})

// GET method route
app.get('/users/create', function (req, res) {
    res.render('users/create')
})

// POST create user
app.post('/users/create', function (req, res) {
    // Add a post
    db.get('users').push(req.body).write()
    res.redirect('/users');
})

// GET method route
app.get('/users/search', function (req, res) {
    var q = req.query.name;
    var matchUsers = db.get('users').value().filter(f => f.name.toLocaleLowerCase().indexOf(q.toLocaleLowerCase()) !== -1);
    res.render('users/index', {
        users: matchUsers
    })
})

app.listen(port, () => console.log(`Example app listening on port ${port}!`))

Ignore nodemon: https://github.com/remy/nodemon/
/nodemon.json (không cho nodemon load file này)
nodemon.json
{
    "ignore": ["db.json"]
}


Command: npm start|

/db.json (Dữ liệu đã được lưu vào file này)
db.json
{
  "users": [
    {
      "name": "wetwtwet"
    }
  ]
}

<< back | next >>

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang