Javascript Ascii Encoding

14,218

Solution 1

For Node.js this is fairly easy:

var keyByte = new Buffer(string, "ascii");

Buffer is a container of bytes, and can be treated as an array:

var bytes = new Buffer("Hello, world", "ascii");
console.log(bytes[3]);  //writes 108

Most of the network and filesystem APIs take and return buffers

Solution 2

Update for NodeJS

const str = 'Hello world';
const buf = Buffer.from(str, 'ascii');
console.log(buf.toString('hex'));
console.log(buf.toString('base64'));
Share:
14,218
Deepak Banka
Author by

Deepak Banka

I work as a Full stack developer in a fast paced Startup environment. I have been involved in web development which includes develping apis by using java,spring,maven for back end developement and enhancing the user experience by using the new age UI frameworks like AngularJS, jQuery, kendoUI,BootStrap. I have also worked in building search functionality in apps which include setting up servers for indexing large amount of data using frameworks like Solr and Elastic Search and using these frameworks to build proper apis for searching data based on the given use case.

Updated on June 04, 2022

Comments

  • Deepak Banka
    Deepak Banka almost 2 years

    How to convert a JavaScript string to byte array using ASCII encoding?

    In C#, it is done as:

     var encoding = new System.Text.ASCIIEncoding();
     byte[] keyByte = encoding.GetBytes(string); 
    

    I want to do the same in JavaScript for my nodejs server