Inheriting through Module.exports in node - javascript

This is probably me being stupid...
I'm using node with express and I have a seperate file using exports for routes. Above it, I require and cast to a variable, a package I have installed using npm.
var passwordHash = require('password-hash');
app.get("/signup", routes.signup);
inside routes.signup, I have:
passwordHash.generate(req.form.username, {algorithm: 'sha512'})
and it throwing an error saying passwordHash is undefined. How can I go about "inheriting" said require call?

You can also do the following (say this code is defined in app.js):
module.passwordHash = require('password-hash');
app.get("/signup", routes.signup);
in routes.signup:
var passwordHash = module.parent.passwordHash; // from app.js
passwordHash.generate(req.form.username, {algorithm: 'sha512'});

Separate files have separate scopes, so if you want to use passwordHash inside of your other file, then you need to call require('password-hash'); in that file too.

You can move your variables via app variable which should be accessible everywhere. Try to do something like that:
app.passwordHash = require('password-hash');
app.get("/signup", routes.signup);
The other thing that you might try is to use global variable, which means removing var from passwordHash. Not sure if this will work out for express, but it's worth checking.
passwordHash = require('password-hash');
app.get("/signup", routes.signup);
Let me know if it helped.

I know this question is old, but this would've helped me: Use exports!
So if I have a file called Index.js with this:
var model = require("./Model");
function test()
{
model.setMyVar("blah");
console.log(model.myVar);
}
My Model.js would look like this:
var myVar;
exports.myVar = myVar;
function setMyVar(value)
{
this.myVar = value;
}
exports.setMyVar = setMyVar;

Related

Cross-module variable in node.js

this question might have been asked already but all I find are specific case and I can't find a way to use the answers to solve my own problem.
What I want is a variable than has a single instance and is shared between modules/files
Let's say I have app.js and module.js
app.js:
var mymodule = require('./modules/mymodule.js');
var testVar = 'test';
...
mymodule.js:
var mymodule = {count:0}
var logCount = function() {console.log(mymodule.count);}
module.exports = mymodule;
Then with this code when app execute mymodule.count = 1, if after mymodules.js run logCount() it will log 1, this means that app and mymodule are sharing the exact same instance of mymodule.count
Now how can mymodule.js access to the same instance as testVar used by app.js in a way that if app.js change it's value, mymodule will have the same new value.
For exemple in normal javascript, if you include two scripts in an html page, as long as the variable isn't inside a function, every javascript file can access the variable, because it works as if all the script would have been pasted inside a single file, isn't there a way to obtain the same result in node?

JavaScript - Instantiate from require

I have a Node program. This program is importing some code. That code looks like the following:
sample.js
function SampleModel() {
this.name = 'Test';
}
module.exports = SampleModel;
I am using SampleModel in another file. Currently, I am successfully using it like this:
another.js
var SampleModel = require('./sampleModel');
var model = new SampleModel();
For the purpose of education, is there a way to condense these two lines down to a single line of JavaScript? If so, how?
Thank you!
Like this:
var model = new (require('./sampleModel'))();
It's quite common to access the required module directly in the import line, but you'll mostly see property access (like require('events').EventEmitter).

meaning of module.exports= function in node.js

I am taking first steps with node.js and obviously one of the first things i tried to do was exporting some data from a module, so i tried this simple case:
dummy.js:
var user = "rally";
module.exports = {
user:user
};
and than required it from a different file like this:
var dummy = require('./dummy.js');
console.log(dummy.user); // rally
So far so good, every thing works, but now i dived into code where there is this definition in the beginning of the module:
module.exports = function(passport,config, mongoose) {}
and i don't understand whats the meaning of it and how can i work with it.
just for trying to understand i defined some variables inside this abstract function but couldn't get their value from any other file.
any idea how can i export variables from module defined like this..? so for example i could require this module and get the "Dummy" variable and use it in a different file
module.exports = function(passport,config, mongoose) {
var dummy = "Dummy";
}
It works exactly the same as the first one does, only that it exports a function instead of an object.
The module that imports the module can then call that function:
var dummy = require('./dummy.js');
dummy();
any idea how can i export variables from module defined like this..?
Since functions are just objects, you can also assign properties to it:
module.exports = function(passport,config, mongoose) {}
module.exports.user = 'rally';
However I'd argue that this is less expected if a module directly exports a function. You are probably better off exporting the function as its own export:
exports.login = function(passport,config, mongoose) {}
exports.user = 'rally';
WHAT IS A MODULE?
A module encapsulates related code into a single unit of code. When creating a module, this can be interpreted as moving all related functions into a file.
// dummy.js
var exports = module.exports = {};
The utility of dummy.js increases when its encapsulated code can be utilized in other files. This is achieved by using exports.
HOW ARE THEY INVOKED?
You could declare your functions outside of the module.exports block. Functions inside exports can be invoked exactly the same way as variables or any other object.
EXAMPLE
//dummy.js
var myVariable = "foo";
var myFunction = function(){
//some logic
};
module.exports{
myVariable : myVariable,
myFunction : myFunction,
myVariableTypeTwo : "bar",
myFunctionTypeTwo : function () {
//some logic
}
}
We can now access the publicly available methods of dummy.js as a property from any js file.
var dummy = require('./dummy.js');
dummy.myVariable; //foo
dummy.myFunction();
dummy.myVariableTypeTwo; //bar
dummy.myFunctionTypeTwo();
NOTE
In the code above, we could have replaced module.exports with exports and achieved the same result. If this seems confusing, remember that exports and module.exports reference the same object.

Is it possible to declare global variables in Node/Express 4.0

I have multiple routes that need to access a database, for development I use a local database, and obviously production I use a hosted database
The only problem is every time I go to push a release I have to go through each route manually changing the database link
e.g.
var mongodb = require('mongojs').connect('urlhere', ['Collection']);
It would be nice if I could declare a variable in app.js like
app.set('mongoDBAddress', 'urlhere');
then in each file do something like
var mongodb = require('mongojs').connect(app.get('mongoDBAddress'), ['Collection']);
Does anybody know if this is achievable I've been messing around with it for about an hour googling and trying to include different things but I have no luck. thanks.
From the docs:
In browsers, the top-level scope is the global scope. That means that
in browsers if you're in the global scope var something will define a
global variable. In Node this is different. The top-level scope is not
the global scope; var something inside a Node module will be local to
that module.
You have to think a bit differently. Instead of creating a global object, create your modules so they take an app instance, for example:
// add.js
module.exports = function(app) { // requires an `app`
return function add(x, y) { // the actual function to export
app.log(x + y) // use dependency
}
}
// index.js
var app = {log: console.log.bind(console)}
var add = require('./add.js')(app) // pass `app` as a dependency
add(1, 2)
//^ will log `3` to the console
This is the convention in Express, and other libraries. app is in your main file (ie. index.js), and the modules you require have an app parameter.
You can add a global variable to GLOBAL, see this this question, although this is probably considered bad practice.
We have two methods in node.js to share variables within modules.
global
module.export
But your problem seems to be different, what I got is you want to connect your application to different databases without changing code. What you need to do is use command line params
For more ref
server.js
var connectTo = {
dev : "url1"
production : "url2"
}
var mongodb = require('mongojs').connect(connectTo[process.argv[2]], ['Collection']);
Run your server.js as
node server.js dev
// for connecting to development database
or
node server.js production
// for connecting to prodiction database
To share connection across diffrent modules
//Method 1
global.mongodb = require('mongojs').connect(connectTo[process.argv[2]], ['Collection']);
//Method 2
exports.mongodb = require('mongojs').connect(connectTo[process.argv[2]], ['Collection']);
exports.getMongoDBAddress = function() {
return connectTo[process.argv[2]]
}

Express - Passing mysql connection to scripts

I defined mysql connection with all parameters necessary to app.js, how can make visible to other scripts in routes/ by default, without requiring or redefining mysql parameters, just using client.query(..)?
A pattern I use is to set up my db object in a module once and export it: (let's call it utils/mySQL.js)
//I haven't used real mysql in node so excuse the pseudo-syntax:
var db = require('mysql-driver-thingy');
db.connect('localhost', 'sqlport', options...);
db.otherSetupFunctions();
console.log("Finished db setup. You should only see this message once! Cool.");
module.exports = db;
And then I can require the db object everywhere I need it. Since requires are cached, this does't actually call the setup methods multiple times.
In app.js:
var db = require('./utils/mySQL.js');
...
In models/user.js:
var db = require('../utils/mySQL.js');
...
A final option, which isn't recommended, is to pollute the global namespace. This seems to be the answer you're really after:
//set up your db
...
// and now make it available everywhere:
global.client = db.client
You can now magically use the client object in all your modules, without even requiring it.
There are many reasons globals are bad, though:
If your code and other code define globals, they could conflict and overwrite each other.
It's hard to find where you defined the db/client object, etc.
You can inject mysql connection into other scripts like this:
app.js
var mysqlConnection = new Conection(params);
require('controller/main.js)(mysqlConnection);
main.js
module.exports = function(mysqlConnection) {
// You can access your mysql connection here
};
UPDATE:
You can inject several variables same way. Also you still can export methods from module if you need this:
app.js
var mysqlConnection = new Conection(params);
var news = require('model/news.js)(app, mysqlConnection);
news.list(function(err, news) {
// Do something
});
news.js
module.exports = function(app, mysqlConnection) {
var methods = {};
// mysql connection and app available from here
methods.list = function(cb) {
mysqlConnection.list(function(err, data) {
cb(err, data);
});
};
return methods;
};

Categories

Resources