将string转换为js中的hex

即时通讯使用node.js和我有一个string,我试图将其转换为hex。

这是我正在使用的function:

function toHex(str) { var hex = ''; var i = 0; while(str.length > i) { hex += ''+str.charCodeAt(i).toString(16); i++; } return hex; } 

这就是我想要的:

 console.log('Payload: ' + toHex(decryptedPayload)); 

但是,当它运行我得到这个错误:

  hex += ''+str.charCodeAt(i).toString(16); ^ TypeError: undefined is not a function at toHex (C:\Users\Office\Desktop\luigi-master\lib\middleware.js:131:17) at Middleware._transform (C:\Users\Office\Desktop\luigi-master\lib\middleware.js:161:29) at Middleware.Transform._read (_stream_transform.js:179:10) at Middleware.Transform._write (_stream_transform.js:167:12) at doWrite (_stream_writable.js:301:12) at writeOrBuffer (_stream_writable.js:288:5) at Middleware.Writable.write (_stream_writable.js:217:11) at Packetize.ondata (_stream_readable.js:540:20) at Packetize.emit (events.js:107:17) at readableAddChunk (_stream_readable.js:163:16) 

如果你有一个Buffer,你可以直接调用toString()并传递你想要的输出,例如: decryptedPayload.toString('hex')