Node.js consoling concern regarding backslashes

154 views Asked by At

This issue is not of high importance, however, I have found that when logging backslashes to the console, values are not outputted as expected.

Please attempt the following two examples in your terminal to confirm the results; I have tried versions 0.10 and 0.12, and have also tried substituting '\\' with equivalents such as UTF hex codes and character codes... The behaviours are the same.

Example one using String.replace(). I found this unexpected behaviour initially using a regex pattern, similar to .replace(/([*\-\[\] etc...])/g, '\\$&'), however, the below code simplifies this scenario.

var bcks = '\\', str = 'Hello*';
console.log('Backslash', bcks, '\nString', str);
str.replace('*', bcks);

The output of which is the following:

Backslash \
String Hello*
'Hello\\'

Example two whilst using backslashes in a value in an object. This case was also found whilst using a .replace(etc ...), but after reducing it to the following, the unexpected behaviour is still apparent.

var tmp = {key: 'Hello\\'}; console.log(tmp); console.log(tmp.key);

The output of which is the following:

{ key: 'Hello\\' }
Hello\

It may be that stdout is simply the cause of this behaviour, but if this not the case then my concern is that this issue is not limited to just logging.

Can anybody explain this behaviour?


Edit: In both examples, at no point should a consoled string, or object, output a double backslash.

1

There are 1 answers

3
Scimonster On

This is limited to using Node's REPL. It seems to do some weird escaping thing... sometimes.

If you just type bcks, it will return the copyable value '\\'. However, if you console.log() it, it logs its actual value: \.

I think it might be doing something similar to JSON.stringify().