I
I
Ivanus2016-04-07 14:49:21
JavaScript
Ivanus, 2016-04-07 14:49:21

How to make a generic Node JS module?

There is a database module

function createBD(){
    console.log('create BD');
};

exports.createBD = createBD;

The application is launched like this: node project.js
And declared in project.js: var bd = new bd.createBD();
Other modules are also connected in project.js, the question is how to use one created object (one module) in all connected modules, that is, not to create a new database object in each module (var bd = new bd.createBD() ;), but connect it once and use it in the connected modules of one project?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Valentin Dubrovsky, 2016-04-07
@matroskin13

function createBD(){
console. log('create BD');
};
module.exports = new createDB();

T
tex0, 2016-04-07
@tex0

var bd = new bd.createBD();
//update: SomeModule - загруженный через require модуль
var mModule = new SomeModule(bd);

--- any module that uses the bd object is styled like this ----
------- SomeModule ---------
var lDb = undefined;

module.exports = function(dbObject)
{
    // как-то проверяем значение dbObject. Если не допустимое значение - ошибка
    lDb = dbObject;// внутренний объект bd
    // тут объекты, методы текущего модуля
   ...
}

You can try like this.

T
Timur Shemsedinov, 2016-04-08
@MarcusAurelius

Use the Global, Luke!

// In application entry point or framework
global.api = {};
api.fs = require('fs');
api.http = require('http');
require('./db');
require('./application');
global.db = new api.db.createDatabase();

// In DB module: db.js
api.db = {};
api.db.createDatabase = function() {
  console.log('Create DB');
};

// In any place and any applied module
db.select('.....or whatever you want');

It is also good to master sandboxes for escaping modules and application code in different globals: https://github.com/HowProgrammingWorks/InversionOf...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question