How to DRY requires in a Node Express app? - node.js

I have a Node + Express app. In many of my files I am doing this at the top
const config = require('./config');
const Twit = require('twit');
const TwitConnector = new Twit(config);
Is there a way to DRY this, so I don't have to repeat this everywhere?
Is there a, best practice, pattern to make something like TwitConnector globally available so that I can use it anytime I need it?
Or maybe that's not a good idea and explicitly requiring it is the right thing to do?

Can't you make twit-connector.js file and require that instead? I don't think making it global is a good idea.
twit-connector.js
const config = require('./config');
const Twit = require('twit');
const TwitConnector = new Twit(config);
module.exports = TwitConnector;
somefile.js
const TwitConnector = require('./twit-connector');
// do something with TwitConnector

Related

Is it possible to keep an instance on Node.js across an entire app?

I want to instantiate a class in a module like this:
const Agenda = require('agenda');
const agenda = new Agenda({db: {address: mongoConnectionString}});
and then access the agenda already configured object from everywhere else in the code (like a singleton). At first I thought about using module.exports = agenda; but then when I require this module in another module of the application it will execute all the code again right?
So, if I'm not wrong which is the best approach to achieve this? Thanks.
You can use global object to share variables everywhere in your node application:
const Agenda = require('agenda');
const agenda = new Agenda({db: {address: mongoConnectionString}});
global.agenda = agenda;
And then you can get your agenda in another module like this:
const agenda = global.agenda;

Instantiating express

I have an issue where I need to load express like this:
var express = require('express');
var app = express();
In order to get .static to work:
app.use(express.static(__dirname+'views'));
Any reason why I can't use shorthand:
var app = require('express')();
When I try the short hand it says express.static is undefined and my script won't run. Is this just a feature that's not supported by express?
Any reason why I can't use shorthand:
var app = require('express')();
If you considered this statement from your script,
app.use(express.static(__dirname+'views'));
you are using static method of express.In order to use this method,you must import express first and store it in some variables like u did
var express = require('express');
From express#express.js
exports.static = require('serve-static');
static defined at class level.
then instantiate it
like this
var app = express();
to get the access to object level(prototype) method and properties like
app#use app#engine etc.
From express#application //line no 78
EDIT :
but then why can't I use app.static if I did var app = require('express')();
As I said,.static is the class level method and not the instance/object(prototype) level.
So,by var app = require('express')()
you will get express instance / object (prototype) which dont have app.static method.So,you can't use.
Read more javascript-class-method-vs-class-prototype-method
This will work: const app = (() => require('express'))()();
But you still need express itself, so there literally is no real point to requiring twice.

How to give folder path in require in express js

My project skeleton,
-app
|_modules
|_test
|_test.js
my test.js
var chai = require('chai');
var chaiHttp = require('chai-http');
var server = require('../modules');
var should = chai.should();
chai.use(chaiHttp);
error
Error: Cannot find module '../modules'
Can some one please help me........Thanks.
You cannot require an entire folder, but a specific file, such as:
var server = require('../_modules/server.js');
Mind you, the module you're requiring should have defined exports. For further detail, I recommend reading the official documentation: https://nodejs.org/api/modules.html.

Express js Where do the settings go?

In the express docs, there is a section called settings:
http://expressjs.com/api.html#app-settings
But I can't figure out where exactly the should go (to some function? as a dictionary in the use middleware? or somewhere else?)
P.S. How would I go about figure theses things out - do I need to look at source?
There are many ways to manage configuration, but here's a blog post I wrote about it:
http://www.chovy.com/node-js/managing-config-variables-inside-a-node-js-application/
The basic premise is you have a file for each environment (ie config.development.js, config.production.js) and one for everything else called config.global.js the development and production files would simply overwrite whatever you set in the global based on the needs of that environment.
Here’s the basic config/index.js file, this will load the config.test.js file assuming your NODE_ENV=test (we will default to ‘development’ if NODE_ENV is not defined):
var env = process.env.NODE_ENV || 'development'
, cfg = require('./config.'+env);
module.exports = cfg;
Next comes the config.test.js which will include config.global.js and then overwrite it’s json objects as needed:
config.test.js:
var config = require('./config.global');
config.env = 'test';
config.hostname = 'test.example';
config.mongo.db = 'example_test';
module.exports = config;
And the config.global.js which defines all the defaults:
var config = module.exports = {};
config.env = 'development';
config.hostname = 'dev.example.com';
//mongo database
config.mongo = {};
config.mongo.uri = process.env.MONGO_URI || 'localhost';
config.mongo.db = 'example_dev';
Now we wrap it all together and use it in our code…for example in a model, you might do something like this in ./models/user.js:
var mongoose = require('mongoose')
, cfg = require('../config')
, db = mongoose.createConnection(cfg.mongo.uri, cfg.mongo.db);
And that’s all there is to it.
You have to use app.set:
app.set('name of setting', 'value');
You usually put them into a specific configuration block:
app.configure(function () {
// ...
});
You can even use named blocks for having different configurations.
Let express create an application for you and have a look at it. For that simply run
$ express --help
at the command prompt and see what it offers.
PS: This answers both of your questions ;-)

How can I pass a variable while using `require` in node.js?

In my app.js I have below 3 lines.
var database = require('./database.js');
var client = database.client
var user = require('./user.js');
user.js file looks just like ordinary helper methods. But, it needs interact with database.
user.js
exports.find = function(id){
//client.query.....
}
Apparently, I want to use client inside of the user.js file. Is there anyway that I can pass this client to the user.js file, while I am using require method?
I think what you want to do is:
var user = require('./user')(client)
This enables you to have client as a parameter in each function in your module
or as module scope variable like this:
module.exports = function(client){
...
}
This question is similar to: Inheriting through Module.exports in node
Specifically answering your question:
module.client = require('./database.js').client;
var user = require('./user.js');
In user.js:
exports.find = function(id){
// you can do:
// module.parent.client.query.....
}
You should just put the same code in user.js
app.js
var client = require('./database.js').client; // if you need client here at all
var user = require('./user.js');
user.js
var client= require('./database.js').client;
exports.find = function(id){
//client.query.....
}
I don't see any drawbacks by doing it like this...
Why do you use require, for scr, no prom use source. It's the same as require and we can pass args in this fuction.
var x="hello i am you";
console.log(require(x)); //error
console.log(source(x)); //it will run without error

Resources