什么是NodeJs相当于Java的getBytes()

What is the NodeJs equivalent to Java getBytes()

本文关键字:getBytes Java NodeJs 相当于 什么      更新时间:2023-09-26

我需要在NodeJs中执行Java函数。

string.getBytes()

在Java中,这将字符串转换为字节数组byte[]

@Eranga Kapukotuwa我不知道你是否还需要这个问题的答案,但是我已经在我的一个项目中使用了下面的代码来完成这项工作,它工作得很完美。

var getBytes = function (string) {
var utf8 = unescape(encodeURIComponent(string));
var arr = [];
for (var i = 0; i < utf8.length; i++) {
    arr.push(utf8.charCodeAt(i));
}
console.log('Array ', arr);
return arr;
}

你可以试着做同样的事情

Class Method: Buffer.byteLength(string[, encoding])#
  • 字符串的字符串
  • 编码字符串,可选,默认值:'utf8'
  • 返回:数量

    Buffer.byteLength(str, 'utf8')
    

这应该有帮助:

> s = 'あhello'
'あhello'
> s.split('').forEach(function(c,i) { console.log(s.charCodeAt(i) + " " + c); });
12354 あ
104 h
101 e
108 l
108 l
111 o
undefined
// Or as one line
s.split('').map(function(c,i) { return s.charCodeAt(i) }).reduce(function(a, b) {return a.toString(16) + " " + b.toString(16)})