NodeJS escaping back slash

2019-07-27 23:51发布

问题:

I am facing some issues with escaping of back slash, below is the code snippet I have tried. Issues is how to assign a variable with escaped slash to another variable.

var s = 'domain\\username';
var options = {
    user : ''
};
options.user =  s;

console.log(s); // Output : domain\username - CORRECT
console.log(options); // Output : { user: 'domain\\username' } - WRONG

Why when I am printing options object both slashes are coming?

I had feeling that I am doing something really/badly wrong here, which may be basics.

Update:

When I am using this object options the value is passing as it is (with double slashes), and I am using this with my SOAP services, and getting 401 error due to invalid user property value.

But when I tried the same with PHP code using same user value its giving proper response, in PHP also we are escaping the value with two slashes.

回答1:

When you console.log() an object, it is first converted to string using util.inspect(). util.inspect() formats string property values as literals (much like if you were to JSON.stringify(s)) to more easily/accurately display strings (that may contain control characters such as \n). In doing so, it has to escape certain characters in strings so that they are valid Javascript strings, which is why you see the backslash escaped as it is in your code.



回答2:

The output is correct.

When you set the variable, the escaped backslash is interpreted into a single codepoint.

However, options is an object which, when logged, appears as a JSON blob. The backslash is re-escaped at this point, as this is the only way the backslash can appear validly as a string value within the JSON output.

If you re-read the JSON output from console.log(options) into javascript (using JSON.parse() or similar) and then output the user key, only one backslash will show.

(Following question edit:)

It is possible that for your data to be accepted by the SOAP consuming service, the data needs to be explicitly escaped in-band. In this case, you will need to double-escape it when assigning the value:

var s = 'domain\\\\user'

To definitively determine whether you need to do this or not, I'd suggest you put a proxy between your working PHP app and the SOAP app, and inspect the traffic.