Home > OS >  How do I use new line characters (\n) with command line arguments in node?
How do I use new line characters (\n) with command line arguments in node?

Time:12-20

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?

CodePudding user response:

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.

  • Related