I need to write the string \n (not a new line, but the literal string) to a file. Any ideas how to do this?
3 Answers
Escape characters in javascript and node.js is \ backslash.
Therefore put one extra \ backslash before your string \n
String: \\n
Output: \n
Comments
As others have mentioned, you need to escape the backslash (\). You can do it like this:
const literalNewline = `This is a newline character: \\n`;
fs.writeFileSync('newline.txt', literalNewline);
Without the escaped backslash I get this:
This is a newline character:
When I escape the character I get the result I'm looking for:
This is a newline character: \n
"\\n". The escape sequence for a literal backslash is two backslashes.