Reputation: 41
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?
Upvotes: 4
Views: 3747
Reputation: 48258
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;
Upvotes: 1
Reputation: 10498
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'});
Upvotes: 5
Reputation: 489
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.
Upvotes: 1
Reputation: 161517
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.
Upvotes: 1