使用Node.Js模块,如何在同一模块中使用对象函数?

时间:2018-09-25 00:00:52

标签: javascript node.js node-modules

我有一个身份验证模块,其中包含我想在整个服务器上使用的方法。我想在模块本身中使用rndString()方法,并将其导出以在整个应用程序中以其他方式使用。我做错了什么导致它不起作用?

const crypto = require('crypto');

let sha512 = (password, salt) => {
    let hash = crypto.createHmac('sha512', salt);
    hash.update(password);
    let value = hash.digest('hex');
    return {
        salt: salt,
        passwordHash: value
    }
};

module.exports = {
    rndString: (length) => {
        return crypto.randomBytes(Math.ceil(length/2))
            .toString('hex')
            .slice(0,length);
    },
    hashId: (id) => {
        let key  = crypto.createCipher('aes-128-cbc', 'kranky');
        let hash = key.update(id, 'utf8', 'hex');
        hash += key.final('hex');
        return hash;
    },
    saltPass: (userpassword) => {
        let salt         = this.rndString(16);
        let passwordData = sha512(userpassword, salt);
        return {
            hashValue: passwordData.passwordHash,
            salt: passwordData.salt
        }
    },
    userSalt: (userpassword, salt) => {
        let passwordData = sha512(userpassword, salt);
        return passwordData.passwordHash;
    }
};

1 个答案:

答案 0 :(得分:2)

在这里分配给对象键的函数中,将rndString函数引用为this.rndString

saltPass: (userpassword) => {
    let salt         = this.rndString(16);
    let passwordData = sha512(userpassword, salt);

在这种情况下,this实际上是指函数,而不是嵌套函数的对象。您也可以使用ES6方法语法来获取正确的上下文:

module.exports = {
  rndString(length) {
    return crypto.randomBytes(Math.ceil(length/2))
        .toString('hex')
        .slice(0,length);
  },
  hashId(id) {
    let key  = crypto.createCipher('aes-128-cbc', 'kranky');
    let hash = key.update(id, 'utf8', 'hex');
    hash += key.final('hex');
    return hash;
  },
  saltPass(userpassword) {
    let salt         = this.rndString(16);
    let passwordData = sha512(userpassword, salt);
    return {
        hashValue: passwordData.passwordHash,
        salt: passwordData.salt
    }
  },
  userSalt(userpassword, salt) {
    let passwordData = sha512(userpassword, salt);
    return passwordData.passwordHash;
  }
}

您可以在此处找到有关对象方法速记的良好文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions