Skip to content Skip to sidebar Skip to footer

Inheriting Through Module.exports In Node

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 in

Solution 1:

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:

varpasswordHash=module.parent.passwordHash; // from app.js
passwordHash.generate(req.form.username, {algorithm: 'sha512'});

Solution 2:

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.

Solution 3:

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.

Solution 4:

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");

functiontest()
{
    model.setMyVar("blah");
    console.log(model.myVar);
}

My Model.js would look like this:

var myVar;
exports.myVar = myVar;

functionsetMyVar(value)
{
    this.myVar = value;
}
exports.setMyVar = setMyVar;

Post a Comment for "Inheriting Through Module.exports In Node"