John John - 3 months ago 14
Javascript Question

How to convert string to ASCII format in JavaScript?

I would like to convert regular string to

ASCII format
. This is because I am trying to communicate with the lock controller and it can't only read commands in
ASCII format.


Below is the code:

var port = new SerialPort("COM5", {
baudRate: 38400
});

port.on('open', function() {
port.write('close1', function(err) {
if (err) {
return console.log('Error on write: ', err.message);
}
console.log('message written');
});
});


Essentially I would like to ensure that close1 communicates in ASCII format instead of the string format.

port.write('close1', function(err) {

Answer

Assuming you're using this SerialPort module, the write function accepts

Accepts a Buffer object, or a type that is accepted by the Buffer constructor (ex. an array of bytes or a string).

When you construct a Buffer from a string, you can tell NodeJS what encoding to use; one of the allowed encodings is ascii (the default is utf-8 which is ASCII for characters 32-127).

So:

// NodeJS v4 and earlier
port.write(new Buffer('close1', 'ascii'), function(err) {
  if (err) {
    return console.log('Error on write: ', err.message);
  }
  console.log('message written');
});

As of v6, we're supposed to use Buffer.from instead:

// NodeJS v6 and later
port.write(Buffer.from('close1', 'ascii'), function(err) {
  if (err) {
    return console.log('Error on write: ', err.message);
  }
  console.log('message written');
});
Comments