Reputation: 1288
I have just started playing with nodeJs. At the moment I have such project:
Structure: - app.js - response.js
app.js code:
var callback = require('./response.js');
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var port = process.env.PORT || 3000;
// body parser middleware
app.use(bodyParser.urlencoded({ extended: true }));
// test route
app.get('/', function (req, res) { res.status(200).send('Hello world!') });
app.post('/test', callback);
// error handler
app.use(function (err, req, res, next) {
console.error(err.stack);
res.status(400).send(err.message);
});
app.listen(port, function () {
console.log('Slack bot listening on port ' + port);
});
My response.js is:
module.exports = function (req, res, next) {
return res.status(200).json({
attachments: [{ "test": "test" }})]
});
}
As you can see here I'm using express server to listen for post requests to /test endpoint and responding to those with some test json.
Question: I want to use mongo - to get same data from database and return it with the response when /test endpoint is triggered. Mongodb tutorials directs me to install mongodb npm module and then to include mongodb module and do the rest for example like this:
// Retrieve
var MongoClient = require('mongodb').MongoClient;
// Connect to the db
MongoClient.connect("mongodb://localhost:27017/exampleDb", function(err, db) {
if(!err) {
console.log("We are connected");
}
});
Upvotes: 0
Views: 79
Reputation: 240
Yes, you can require mongodb in response.js and it should be outside exports. If you require mongodb in app.js, you will not be able to use it in response.js
Upvotes: 0
Reputation: 294
You can require in each module whatever you want. use require only outside from all scopes(Not in function) as it sync method and will block your server. Also it's ok to require same module in multiple other modules. node js knows not to recompile it.
Hope it was helpful.
Upvotes: 1