4

I need to perform a Java function in NodeJs.

string.getBytes()

In Java, this translates a string to a byte array byte[].

Ashish Kakkad
  • 23,586
  • 12
  • 103
  • 136
Eranga Kapukotuwa
  • 4,542
  • 5
  • 25
  • 30
  • 1
    Maybe the iconv module can help? What encoding do you need? Unicode-based things are probably not too difficult (you can get the codepoints with string.codePointAt() ) ? – Thilo Aug 28 '15 at 05:27
  • 1
    Since many proficient Javascript/nodejs developers may not know Java, perhaps you could describe what `getBytes()` does so more of us might know what nodejs features could be a substitute. – jfriend00 Aug 28 '15 at 05:29
  • 1
    Take a look at this: http://stackoverflow.com/questions/6226189/how-to-convert-a-string-to-bytearray – Thilo Aug 28 '15 at 05:30
  • 1
    And also this http://stackoverflow.com/questions/7094615/nodejs-convert-string-to-buffer – brandonscript Aug 28 '15 at 05:31
  • @jfriend00 In Java, this translates a string to a byte array byte[]. – Eranga Kapukotuwa Aug 28 '15 at 05:41
  • Why not use Buffer?, e.g. var b = new Buffer(str); – Teemu Ikonen Aug 28 '15 at 06:16

3 Answers3

5

@Eranga Kapukotuwa I don't know if you still need an answer for this question but I have used the below code to get this work done in one of my projects and it works perfect.

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;
}
Syn3sthete
  • 4,151
  • 3
  • 23
  • 41
1

You can try to do the same

Class Method: Buffer.byteLength(string[, encoding])#
  • string String
  • encoding String, Optional, Default: 'utf8'
  • Return: Number

    Buffer.byteLength(str, 'utf8')
    
SaviNuclear
  • 886
  • 1
  • 7
  • 19
0

This should help:

> 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)})
John Estess
  • 576
  • 10
  • 22