来自函数的节点 crypto.randomBytes return 令牌
Node crypto.randomBytes return token from function
总结
我有一个函数,我在其中使用 crypto.randomBytes 生成令牌,但我在 return 从该函数中获取令牌时遇到问题。我想从 createResetToken 获取 return 令牌。我的功能在下面,我尝试了很多不同的东西,但它们没有用。任何帮助将不胜感激!
代码
function createResetToken() {
crypto.randomBytes(20, function(err, buf) {
const token = buf.toString("hex");
console.log("token inside inside", token);
return token;
});
}
最简单的方法是使用 randomBytes() 的同步方式,你可以通过不提供回调函数来实现:
function createResetToken() {
return crypto.randomBytes(20).toString("hex");
}
通过文档:
If a callback function is provided, the bytes are generated
asynchronously and the callback function is invoked with two
arguments: err and buf. If an error occurs, err will be an Error
object; otherwise it is null. The buf argument is a Buffer containing
the generated bytes.
...
If the callback function is not provided, the random bytes are
generated synchronously and returned as a Buffer. An error will be
thrown if there is a problem generating the bytes.
总结
我有一个函数,我在其中使用 crypto.randomBytes 生成令牌,但我在 return 从该函数中获取令牌时遇到问题。我想从 createResetToken 获取 return 令牌。我的功能在下面,我尝试了很多不同的东西,但它们没有用。任何帮助将不胜感激!
代码
function createResetToken() {
crypto.randomBytes(20, function(err, buf) {
const token = buf.toString("hex");
console.log("token inside inside", token);
return token;
});
}
最简单的方法是使用 randomBytes() 的同步方式,你可以通过不提供回调函数来实现:
function createResetToken() {
return crypto.randomBytes(20).toString("hex");
}
通过文档:
If a callback function is provided, the bytes are generated asynchronously and the callback function is invoked with two arguments: err and buf. If an error occurs, err will be an Error object; otherwise it is null. The buf argument is a Buffer containing the generated bytes.
...
If the callback function is not provided, the random bytes are generated synchronously and returned as a Buffer. An error will be thrown if there is a problem generating the bytes.