简体   繁体   English

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

[英]Node.js module.exports a function with input

I have a little encryption file that adds a encrypted random number after some inputs:我有一个小的加密文件,它在一些输入后添加了一个加密的随机数:

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

The returned value is undefined when I export it to another file and console.log it当我将它导出到另一个文件和 console.log 时,返回的值是未定义的

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

What did I do wrong here?我在这里做错了什么?

I also have tried我也试过

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

No luck.没运气。

Thanks in advance.提前致谢。

You can use promises to handle the async functions您可以使用承诺来处理异步功能

Try Changing your module.exports to return a promise function尝试更改您的 module.exports 以返回一个承诺函数

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

You can then call the promise function using the promise chain然后你可以使用promise链调用promise函数

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

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

Suggest you to read Promise documentation建议你阅读Promise 文档

For node version > 8, you can use simple async/await without promise chain.You have to wrap your api inside a promise using utils.promisify (added in node 8) and your function should use the keyword async .Errors can be handled using try catch对于节点版本 > 8,您可以使用简单的async/await而不使用承诺链。您必须使用utils.promisify (在节点 8 中添加)将您的 api 包装在承诺中,并且您的函数应使用关键字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));

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

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