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
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
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
let e = require("./encryption.js");
e(1, 2).then((res) => {
console.log(res);
}).catch((e) => console.log(e));
Suggest you to read Promise documentation
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
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));