0

I have some files:

tags.js:

var express = require('express'),
    router = express.Router(),
    monk = require('monk'),
    db = monk('localhost:27017/data');

...

module.exports = router;

records.js:

var express = require('express'),
    router = express.Router(),
    monk = require('monk'),
    db = monk('localhost:27017/data');

...

module.exports = router;

users.js:

var express = require('express'),
    router = express.Router(),
    monk = require('monk'),
    db = monk('localhost:27017/data');

...

module.exports = router;

All the time I have to duplicate my header:

var express = require('express'),
    router = express.Router(),
    monk = require('monk'),
    db = monk('localhost:27017/data');

What's the best solution to connect this configuration variables just once?


I tried this variant In Node.js, how do I "include" functions from my other files?, but that doesn't work, becouse I should use require (for example: require('express')) in tools.js and I got errors.

I also tried this variant node.js - accessing required variables from other files:

toolkit.js:

var express = require('express'),
    router = express.Router(),
    monk = require('monk'),
    db = monk('localhost:27017/data');

tags.js:

var tools = require('../toolkit'),
    router = tools.router;

router.get('/', function(req, res) {
...
});

module.exports = router;

but I got errors again.

1 Answer 1

1

You need to export from toolkit.js. So, your toolkit will look like

var express = require('express');
exports.router = express.Router();
var monk = require('monk');
exports.db = monk('localhost:27017/data');

Now, you can do:

var toolkit = require('path/to/toolkit');
var router = toolkit.router;
var db = toolkit.db;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.