stevenelberger
stevenelberger

Reputation: 1368

fs.writeFileSync Doesn't Write String With Escaping Backslashes

In my program I'm trying to write a string that represents a regular expression exactly as it is written into a file. This means preserving any backslashes that occur in the string. However, when I try to write this string to a file, each pair of backslashes has one less backslash than it should.

My example to demonstrate this problem is like so:

let filepath = path.join(__dirname, 'output.js');
let outputString = "\\d{3}(-|\\s)?\\d{3}(-|\\s)?\\d{4}";
fs.writeFileSync(filepath, outputString, 'utf-8');

The output result is:

\d{3}(-|\s)?\d{3}(-|\s)?\d{4}

Is there some option I can pass to fs.writeFileSync to maintain all characters in the string to write to the file?

I realize one solution might involve escaping all possible characters in this string with a library like js-string-escape, but since these particular strings represent regular expressions is it really safe to do so? I don't want to alter them or their functionality in any way.

note: I realize this output isn't really valid JavaScript, but it's a somewhat contrived example of what I am really trying to do. This small snippet of code just best demonstrates the issue at hand.

Upvotes: 2

Views: 2627

Answers (1)

Zero
Zero

Reputation: 533

If you want two backslashes in the outputString, four backslashes are nedded. Ex.:

let filepath = path.join(__dirname, 'output.js');
let outputString = "\\\\d{3}(-|\\\\s)?\\\\d{3}(-|\\\\s)?\\\\d{4}";
fs.writeFileSync(filepath, outputString, 'utf-8');

The output result will be:

\\d{3}(-|\\s)?\\d{3}(-|\\s)?\\d{4}

One backslash skip the follow backslash...

Upvotes: 2

Related Questions