2017-09-27 8 views
0

私はnodejsのデータベースとしてlowdbを使用しています。 1つのファイルにすべてがありましたが、今はデータベースを別のファイルにアウトソーシングしたいと思います。データベース操作/ノードJ内の異なるファイルへの接続をアウトソーシングしますか?

私はデータベースにアクセスする必要のあるさまざまな機能を持っています。今、私の外部委託されたファイルは次のようになります。

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"); 
    }, 
}; 

私は本当に私は、他のファイルで、このファイルを含めることができる方法を理解していない、まだ上記のように、私のmodule.exportを使用しています。私はファイルを必要とし、そのままモジュールのエクスポートを残しますか?あるいは私は別のアプローチが必要でしょうか?

答えて

0

あなただけのutil dirのように、どこかにあなたのプロジェクト構造でdb.jsファイルを作成し、ちょうどそのよう、dbオブジェクトをエクスポートすることができます。

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; 

その後、別のファイルからそれを必要と

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

db.get('tags') 
.push({ id: 1, title: 'lowdb is awesome'}) 
.write()  
関連する問題