简体   繁体   中英

For every letter in a string, print its ascii character representation

I am reading from a socket and trying to debug some of the messages which are coming in. Right now, I am trying to see if there is any "invisible" letters sneaking past my regex. I do the following in order to get the literal string values.

socket.on('data', function (data) {
  const message = data.toString('ascii');
  let characters = [];
  message.forEach((letter, i) => characters.push(message.charCodeAt(i)));
  console.log(characters);
});

The result looks like this:

[58, 13, 10, 26]

I want to get something more human readable without a (manual) look up of each letter on an ascii table. That is, the list would look more like this:

[':', '\r', '\n', 'ctrl-z']
// or
[':', 'carriage return', 'new line', 'substitution']

Is there any way of accomplishing this with Node.js?

In node 5.1, you can just split the string into an array of characters and console.log the array. The built in console.log will print escape codes for non printing characters:

socket.on('data', function(data){
    const message = data.toString('ascii');
    console.log(message.split(''))
})

If you are using a lower version of node, you can use the util package in node to get a string literal representation of your character.

Something like this should work:

socket.on('data', function(data){
    const message = data.toString('ascii');
    console.log(message.split('').map(function(c){
        return require('util').inspect(c);
    }))
})

使用message.charAt(i)代替charCodeAt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM