简体   繁体   English

通过节点中的Module.exports继承

[英]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. 我正在使用带有express的节点,我有一个单独的文件使用导出路由。 Above it, I require and cast to a variable, a package I have installed using npm. 在它上面,我需要并转换为变量,我使用npm安装的包。

var passwordHash = require('password-hash');
app.get("/signup", routes.signup);

inside routes.signup, I have: 在routes.signup里面,我有:

passwordHash.generate(req.form.username, {algorithm: 'sha512'})

and it throwing an error saying passwordHash is undefined. 并且它抛出一个错误,说passwordHash是未定义的。 How can I go about "inheriting" said require call? 我怎么去“继承”说要求电话?

You can also do the following (say this code is defined in app.js): 您还可以执行以下操作(例如,此代码在app.js中定义):

module.passwordHash = require('password-hash');
app.get("/signup", routes.signup);

in routes.signup: 在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'); 单独的文件有不同的范围,所以如果你想在你的其他文件中使用passwordHash ,那么你需要调用require('password-hash'); in that file too. 在该文件中也是如此。

You can move your variables via app variable which should be accessible everywhere. 您可以通过app变量移动变量,该变量应随处可访问。 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. 您可能尝试的另一件事是使用全局变量,这意味着从passwordHash中删除var。 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: 所以如果我有一个名为Index.js的文件:

var model = require("./Model");

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

My Model.js would look like this: 我的Model.js看起来像这样:

var myVar;
exports.myVar = myVar;

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM