Javascript 如何使用Node.js将字节数组转换为字符串?
我需要一个随机的字节序列来创建密码散列。在Ruby中,这看起来像:Javascript 如何使用Node.js将字节数组转换为字符串?,javascript,node.js,Javascript,Node.js,我需要一个随机的字节序列来创建密码散列。在Ruby中,这看起来像: File.open("/dev/urandom").read(20).each_byte{|x| rand << sprintf("%02x",x)} 但问题是,如何将它们转换为字符串 还有,我需要用期票把它们包起来。这是否有效: get_rand() .then(function(bytes) { authToken = bytes; }) 试试这个: new Buffer(byt
File.open("/dev/urandom").read(20).each_byte{|x| rand << sprintf("%02x",x)}
但问题是,如何将它们转换为字符串
还有,我需要用期票把它们包起来。这是否有效:
get_rand()
.then(function(bytes) {
authToken = bytes;
})
试试这个:
new Buffer(bytes).toString('ascii');
此处有更多详细信息:是否将其转换为ASCII?如果没有,这是我的代码(工作1分钟):
varz;
randomSource.getRandomBytes(20,函数(){z=参数[0]})
Z
字符串(z)
'�d\u0003�-\'}��\u0014�H��F�Z��/'
randbytes
异步工作。如果要将其与承诺结合起来,还需要使用承诺库。我举一个例子:
var when = require('when');
var RandBytes = require('randbytes');
var randomSource = RandBytes.urandom.getInstance();
function get_rand() {
var dfd = when.defer();
randomSource.getRandomBytes(20, function(bytes) {
dfd.resolve( bytes.toString('hex') ); // convert to hex string
});
return dfd.promise;
}
// example call:
get_rand().then(function(bytes) {
console.log('random byte string:', bytes);
});
您只需使用节点随附的加密:
var Promise = require("bluebird");
var crypto = Promise.promisifyAll(require("crypto"));
crypto.randomBytesAsync(20).then(function(bytes){
console.log('random byte string:', bytes.toString("hex"));
});
日志:
如果您使用的是ES6,那么它也很简单
String.fromCharCode(...bytes)
Promise.resolve(String.fromCharCode(...bytes)) // Promise
或
我喜欢你的回答,因为你提到了了解这个的地方。。。然而,我得到:-为什么这不是“saDasdkn2”嗯。。可能是我正在使用的promise库,我在这里提出了一个问题:
newbuffer(bytes)
不推荐使用,您可以使用newbuffer.from(bytes)
现在这个答案也很好,小细节,我正在使用bluebird库,也许我的问题就在那里,我在这里引用了你的答案:我认为@Esailija的答案实际上是正确的。实际上,这似乎是正确的答案。现在还不确定使用randbytes的好处。它在windows上肯定不起作用。(并不是说有人在乎……;)
var Promise = require("bluebird");
var crypto = Promise.promisifyAll(require("crypto"));
crypto.randomBytesAsync(20).then(function(bytes){
console.log('random byte string:', bytes.toString("hex"));
});
random byte string: 39efc98a75c87fd8d5172bbb1f291de1c6064849
String.fromCharCode(...bytes)
Promise.resolve(String.fromCharCode(...bytes)) // Promise
String.fromCharCode.apply(null, bytes)
Promise.resolve(String.fromCharCode.apply(null, bytes)) // Promise