简体   繁体   中英

Outsourcing database operations / connections to different file in nodejs?

I am using lowdb as my database in nodejs. I had it all in one file, but now I would like to outsource the database into a different file.

I have different functions of which one will have to access the database. Right now my outsourced file looks like this:

const low = require('lowdb')
const FileSync = require('lowdb/adapters/FileSync')

const adapter = new FileSync('db.json')
const db = low(adapter)

db.defaults({ tags: []})
  .write()

module.exports = {
  toCsv: function () {
    console.log("Save to csv");
  },
  toPlainText: function () {
    console.log("Save to plain text");
  },
  toDatabase: function () {
    console.log("Save to Db");
  },
};

I don't really understand how I can include this file in the other file, and the still use my module.export as above. Would I just require the file, and leave the module exports as it is? Or will I need a different approach?

You can just create a db.js file somewhere in your project structure, like a util dir and just export the db object, like that:

const low = require('lowdb')
const FileSync = require('lowdb/adapters/FileSync')

const adapter = new FileSync('db.json')
const db = low(adapter)

db.defaults({ tags: []})
.write()

module.exports = db;

Then, from a different file just require it

const db = require('/path/to/your/db.js')

db.get('tags')
.push({ id: 1, title: 'lowdb is awesome'})
.write()    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM