How to use module in my own node js module? - node.js

How I can use third party module in my own? For example if I have in app main file something like (using body-parser):
app.post("/dothis", (req,res)=>{
var name = req.body.name;
console.log(name);
};
This work fine. But when I want to have this in separate file (for example mod.js), and wrote like this:
exports.own = function(){
var name = req.body.name;
console.log(name);
}
Then in main file wrote:
const mod = require(__dirname + "/mod.js")
app.post("/dothis", (req,res)=>{
mod.own();
};
Then I get error like, req is undefined.
I am trying to add in mod.js file
const {req} = require ("http");
So then I got error that can't read value of name undefined.
There is the question, how i can transfer my code which is using body-parser, express and other modules to separate file or creating own module to get working module?
Thanks!

You are getting undefined because you are not passing the request.
Looking at your code, try this.
exports.own = function(req){ // use request
var name = req.body.name;
console.log(name);
}
const mod = require(__dirname + "/mod.js")
app.post("/dothis", (req,res)=>{
mod.own(req); // pass request
};

Related

getting api keys from module.exports

I have two files a config.js and main.js I am storing api keys in my config.js
like this
function getGoogleApiKey(){
return 'KeyGoogle';
}
function getApiKey(){
return 'keyApi'
}
function getApiKey2(){
return 'keyApi2'
}
module.exports = {
getGoogleApiKey,
getApiKey,
getApiKey2,
}
I would like to get specific keys from the config.js file when I need it. I want to use some keys on my main.js
Here is my main.js.
const {config} = require('./config.js');
const googlePlaces = new GooglePlaces(config.getGoogleApiKey, 'json');
const awesome = new awesome(config.getApiKey);
I am note sure how to get the keys, I also tried it in this way but I get errors.
const {getGoogleApiKey, getApiKey, getApiKey2} = require('./config.js');
const googlePlaces = new GooglePlaces(getGoogleApiKey, 'json');
This line:
const {config} = require('./config.js');
is pulling out a config property from the value returned by require('./config.js'), which is non-existent in config.js.
Instead, just use this:
const config = require('./config.js');
which will assign the exported value (the module.exports object), and will work as expected.
Secondly, functions are being exported and not primitive (string) properties, so one or the other will need to be changed: export string properties directly or convert main.js to use the appropriate function call notation.
For example:
const googlePlaces = new GooglePlaces(config.getGoogleApiKey(), 'json');
const awesome = new awesome(config.getApiKey());

NodeJS (Express) - project structure and mongo connection

I started a new project from scratch with ExpressJS.
Everything works fine but now I begin to have a dozen of 'app.get(....)' function and I need to give the project a structure.
What I have in mind is quite simple, it should have a folder named 'routes' containing a file such as 'module1.js', with all of the app.get related to that module. (like I've seen in many examples)
The issue is how to tell Express to route 'http://url/module1/' to that route file and how to pass it a param variable, containing for instance the mongodb connection.
what I tried is :
var params = {
db: myMongoConnection
};
var mod1 = require('routes/module1');
app.use('/module1', mod1);
but now I still miss the 'params'.
If I try to pass it as an argument to the require method i get an error saying it needs middleware.
Another issue is related to the fact that the myMongoConnection is valid in the connection callback, so I think i need to require and use the route.js inside the MongoClient connect callback.
Any idea?
thanks a lot
For custom modules, create a folder, call it modules
In its index.js, expose the modules that you need.
Something like,
var mods = [
'mod1',
'mod2',
];
function init() {
var expose = {};
var params = {
db: myMongoConnection
};
mods.forEach(mods, function (mod) {
expose[mod] = require('./' + mod)(params);
});
return expose;
}
// export init
module.exports = init;
In mod1.js, wrap the params
module.exports = function(params) {
// all your functions here will have access to params.
}
Then in, server/app.js, require this and set it in the app.
app.set('mods', require('path-to/modules'));
Now, you can access all your modules, using app.get('mods').moduleName.methodname

how to mock twilio in unit tests with either sinon/proxyquire or dependency inejction in node.js

Say I want to test a a user login controller that sends login codes via SMS with Twilio. How should I set up the test so that I can mock Twilio and see what codes it's sending back. My approach was to proxyquire the twilio client object and spy on it with sinon, but I don't think I'm getting it quite right.
controller user.js
var smsClient = new twilio.RestClient(config.get('twilio_account_sid'), config.get('twilio_auth_token'));
module.exports = {
checkCode: function(phone){
var code = getNewCode();
smsClient.sms.messages.create({
from: config.get('twilio_phone_number'),
to: phone,
body: 'Your code :' + code
}, callback);
}
}
test file
var twilioMock = //what goes here??
var smsSpy = sinon.spy(twilioMock.sms.messages, 'create');
var User = proxyquire('../models/user', { 'mongoose': mongooseMock, 'smsClient': twilioMock });
... some describe and it statements ...
twilioMock.sms.messages.should.have.been.calledOnce() //this is where I don't know what I should be checking
// or is this the right way?
//smsSpy.should.have.been.calledOnce()
I am answering this very late but this might help someone.
I haven't used proxywire but it seems very similar to rewire (just by looking at your code). You should try the following:
var twilioMock = new twilio.RestClient(config.get('twilio_account_sid'), config.get('twilio_auth_token'));
I am more used to rewire. npm i rewire --save-dev. Using rewire you may try the following: (concept remains the same)
In your test:
var rewire = require('rewire');
var twilioMock = new twilio.RestClient(config.get('twilio_account_sid'), config.get('twilio_auth_token'));
var userController = rewire('./path_to_user.js') // notice use of rewire
beforeEach(function(){
this.smsClient = twilioMock; // `this` is available within your tests
userController.__set__('smsClient', this.smsClient);
});
it('should something', sinon.test(function(){
var smsSpy = this.spy(this.smsClient.sms.messages, 'create');
}));

java.lang.NoClassDefFoundError at runtime when using express framework and node.js

I am trying to write a sample code to create an instance of a java class and then invoke a method using that instance. I am using node-java module to do this. The code compiles without any error. However when I hit the URL which actually hits the same code then I get the class not found exception.
I have verified that the jar and it is there in the same directory as index.js and the jar also contains the class file (Application.class) for which the instance is being created.
My index.js file
var java = require("java");
java.classpath.push("demo.jar");
var express = require('express');
var router = express.Router();
var Application = java.import('Application');
/* GET home page. */
router.get('/', function(req, res) {
var application = new Application();
var resp = application.getResponse();
res.render('index', { title: resp });
});
module.exports = router;
Sorry for my english. I had the same problem. Look [https://github.com/joeferner/node-java/issues/147]
my code:
`var java = require("java");
var path=require("path");
var fs=require("fs");
console.log("ruta in directory",path.join(__dirname));
console.log("exist file:",fs.existsSync(path.resolve(__dirname,"./lib-java/lib-tgd.jar")));
java.classpath.push("commons-lang3-3.1.jar");
java.classpath.push("commons-io.jar");
java.classpath.push(path.resolve(__dirname,"./lib-java/lib-tgd.jar"));
java.classpath.push(path.resolve(__dirname,"./lib-java/jackson-annotations- 2.5.1.jar"));
java.classpath.push(path.resolve(__dirname,"./lib-java/jackson-core-2.5.1.jar"));
java.classpath.push(path.resolve(__dirname,"./lib-java/jackson-databind-2.5.1.jar"));`
with path.resolve solves the problem of the file path

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