1

I want to make a script that will treat \n character as a literal new line character when given as command line argument. For example if my script is test.js, I want to use node test.js 'Line 1\nLine 2' and get the output as:

Line 1
Line 2

The script I used to test if this works was:

console.log(process.argv[2]);

But when I used it like node test.js 'Line 1\nLine2', it gave me the output as:

Line 1\nLine2

How do I achieve this?

4
  • I don't understand whats stopping you? console.log('line 1\nline 2'); prints exactly what you want. Commented Dec 19, 2021 at 20:23
  • it does when you use it directly, but when you provide the string as an Command line argument it is interpreted as just a character. Commented Dec 19, 2021 at 20:24
  • Some of this may be at the mercy of the shell or command prompt you are using and how it interprets arguments prior to passing them to your program. Commented Dec 19, 2021 at 20:32
  • I am using Linux, I tried bash, sh, and even zsh. All give the same output. Commented Dec 19, 2021 at 20:35

1 Answer 1

3

To explain what's going on, have a look at the following:

const str1 = process.argv[2];
const str2 = '\n';

console.log(Buffer.from(str1)) // prints <Buffer 5c 6e> if '\n' is passed as an argument to the script
console.log(Buffer.from(str2)) // prints <Buffer 0a>

Looking the buffer values up in the ASCII table, you'll find:

10  0a  00001010    &#10;   LF  Line Feed
92  5c  01011100    &#92;   \   backslash
110 6e  01101110    &#110;  n

So as you can see the argument '\n' is not interpreted as a Line Feed character but literally as \ and n.

To fix this, using bash you can pass the argument through $'<...>' expansion forcing escape sequences to be interpreted:

node test.js $'Line1\nLine2'

This will print

Line1
Line2

to the console as expected.

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

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.