Advertisement
braveheart1989

database

May 28th, 2017
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const fs = require('fs')
  2. const path = require('path')
  3. const dbPath = path.normalize(path.join(__dirname, '/database.json'))
  4.  
  5. module.exports.products = {}
  6. module.exports.products.add = (product) => {
  7.   let products = getProducts()
  8.   product.id = products.length + 1
  9.   products.push(product)
  10.   saveProducts(products)
  11. }
  12. let getProducts = () => {
  13.   if (!fs.existsSync(dbPath)) {
  14.     fs.writeFileSync(dbPath, '[]')
  15.     return []
  16.   }
  17.   let json = fs.readFileSync(dbPath).toString() || '[]'
  18.   return JSON.parse(json)
  19. }
  20. let saveProducts = (products) => {
  21.   let json = JSON.stringify(products, null, 2)
  22.   fs.writeFileSync(dbPath, json)
  23. }
  24. module.exports.products.getAll = getProducts
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement