【问题标题】:Node.js module.exports a function with inputNode.js module.exports 带有输入的函数
【发布时间】:2019-09-03 07:34:30
【问题描述】:

我有一个小加密文件,它在一些输入后添加了一个加密的随机数:

const crypto = require("crypto");

module.exports = function (x, y) {
  crypto.randomBytes(5, async function(err, data) {
    var addition = await data.toString("hex");
    return (x + y + addition);
  })
}

当我将它导出到另一个文件并控制台记录它时,返回的值是未定义的

const encryption = require('./encryption')
console.log(encryption("1", "2"));

我在这里做错了什么?

我也试过了

module.exports = function (x, y) {
  var addition;
  crypto.randomBytes(5, function(err, data) {
    addition = data.toString("hex"); 
  })
  return (x + y + addition);
}

运气不好。

提前致谢。

【问题讨论】:

标签: javascript node.js node-modules module-export


【解决方案1】:

你可以使用 Promise 来处理异步函数

尝试改变你的 module.exports 来返回一个 promise 函数

const crypto = require("crypto");
module.exports = function (x, y) {
    return new Promise(function (resolve, reject) {
        var addition;
        crypto.randomBytes(5, function (err, data) {
            addition = data.toString("hex");
            if (!addition) reject("Error occured");
            resolve(x + y + addition);
        })
    });
};

然后您可以使用承诺链调用承诺函数

let e = require("./encryption.js");

e(1, 2).then((res) => {
    console.log(res);
}).catch((e) => console.log(e));

建议你阅读Promise documentation

对于节点版本 > 8,您可以使用简单的 async/await 而不使用 Promise 链。您必须使用 utils.promisify(在节点 8 中添加)将您的 api 包装在 Promise 中,并且您的函数应使用关键字 async。错误可以使用trycatch处理

const util = require('util');
const crypto = require("crypto");
const rand = util.promisify(crypto.randomBytes);

async function getRand(x, y){
    try{
        let result = await rand(5);
        console.log(x + y + result);
    }
    catch(ex){
        console.log(ex);
    }
}

console.log(getRand(2,3));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-08
    • 1970-01-01
    • 2012-04-11
    • 2013-12-30
    • 2021-12-07
    • 2020-07-15
    • 2012-08-31
    • 1970-01-01
    相关资源
    最近更新 更多