Dizio Adil
Dizio Adil

Reputation: 53

Console log ({value}) isn't the same as console.log(value)

I'm not stuck or anything, it's just my own curiosity and I noticed something about Console.log, And I can't find anwsers online , or its limited since I think making a Google search with "{}" isn't really working out

I'm coding a small node.Js app that interacts with Wi-Fi, and I tried the following thing :

console.log(ssid +  " : " + pwd);

and it returns this

freebox_XXXXX : fake_password

So far, everything is normal but then, I was tired and messed up and tried this :

console.log({ ssid: ssid, password: pwd });

and it returned this

 {
  ssid: 'f\x00r\x00e\x00e\x00b\x00o\x00x\x00_\x005\x007\x00a\x002\x00a\x007\x00',
  password: '\x00T\x00e\x00s\x00t\x00'
 }

I'm wondering why do you have any answers?

More details :

The data sent via bluetooth by this function as an bufferArray is created with this function

str2ab(str) {
    let buf = new ArrayBuffer(str.length * 2); // 2 bytes for each char
    let bufView = new Uint16Array(buf);
    for (let i = 0, strLen = str.length; i < strLen; i++) {
      bufView[i] = str.charCodeAt(i);
    }
    return buf;
  }
let payload = str2ab('freebox_XXXXX|' + alertData.password);

Then, the other devices receives it

WriteOnlyCharacteristic.prototype.onWriteRequest = function(data, offset, withoutResponse, callback) {
    let payload = data.toString()

    let wifiData = payload.split('|');

    let ssid = wifiData[0];
    let pwd = wifiData[1];
    console.log(ssid +  " : " + pwd);
    console.log({ ssid: ssid, password: pwd });

   });

Upvotes: 0

Views: 398

Answers (2)

FZs
FZs

Reputation: 18639

The difference is because of how Node.js logs values.

The behaviour of console.log() depends on the type of values being logged:

  • If a string is logged, it is written to stdout as-is (well, not as-is, because %-args are substituted, but that's off-topic for this question), to allow raw texts (optionally with escape sentences) to be displayed in the console
  • If another data type is passed, it will be inspected (intended for debugging, the same way as util.inspect() does it), that is, it will be converted to a format nearly identical to the JS syntax that created it. That makes the strings inside complex data structures displayed as their representation: with quotes around them and special characters escaped.

Your strings contain NULL characters between each letter (that's probably because your code treats a UTF-16 string as UTF-8 or ASCII somewhere), which don't appear when logged to the console, but show up escaped (\x00) when the string is inspected.

That is the cause of the inconsistency between the two logging methods.

Upvotes: 3

Harney
Harney

Reputation: 352

{ ssid: ssid, password: pwd }

It is a object not string.

Upvotes: 0

Related Questions