0

I need to write the string \n (not a new line, but the literal string) to a file. Any ideas how to do this?

4
  • 1
    What's the problem? You don't know how to write to a file, or you don't know how to get a literal backslash + n? Commented Jan 9, 2014 at 22:22
  • Sorry, my mistake. I know how to write a file, but not write \n to said file. Commented Jan 9, 2014 at 22:23
  • 2
    Just escape the character - \\n Commented Jan 9, 2014 at 22:23
  • Like this: "\\n". The escape sequence for a literal backslash is two backslashes. Commented Jan 9, 2014 at 22:24

3 Answers 3

3

Escape characters in javascript and node.js is \ backslash.

Therefore put one extra \ backslash before your string \n

String: \\n

Output: \n

Sign up to request clarification or add additional context in comments.

Comments

1

Assuming you are asking about how to escape the '\n' so it doesn't get interpreted as a newline, that's just doubling the \ character: '\\n'. How to write to a file is a different question.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.