Node.js module.exports 带输入的函数

Node.js module.exports a function with input

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

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

当我将它导出到另一个文件并console.log它

时,返回值未定义
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);
}

运气不好。

提前致谢。

您可以使用 promises 来处理异步函数

尝试将您的 module.exports 更改为 return 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 没有承诺 chain.You 必须使用 utils.promisify 将你的 api 包装在一个承诺中(添加到节点 8 ) 并且您的函数应使用关键字 async。可以使用 try catch

处理错误
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));