如何在节点中将换行符 (\n) 与命令行参数一起使用?
How do I use new line characters (\n) with command line arguments in node?
我想制作一个脚本,在作为命令行参数给出时将 \n
字符视为文字换行符。例如,如果我的脚本是 test.js
,我想使用 node test.js 'Line 1\nLine 2'
并得到输出:
Line 1
Line 2
我用来测试这是否有效的脚本是:
console.log(process.argv[2]);
但是当我像node test.js 'Line 1\nLine2'
那样使用它时,它给我的输出是:
Line 1\nLine2
如何实现?
要解释发生了什么,请查看以下内容:
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>
在 ASCII table 中查找缓冲区值,您会发现:
10 0a 00001010 LF Line Feed
92 5c 01011100 \ \ backslash
110 6e 01101110 n n
因此,正如您所见,参数 '\n'
未被解释为换行符,而是按字面解释为 \
和 n
.
要解决此问题,使用 bash 您可以通过 $'<...>'
传递参数 expansion 强制转义序列被解释:
node test.js $'Line1\nLine2'
这将打印
Line1
Line2
按预期进入控制台。
我想制作一个脚本,在作为命令行参数给出时将 \n
字符视为文字换行符。例如,如果我的脚本是 test.js
,我想使用 node test.js 'Line 1\nLine 2'
并得到输出:
Line 1
Line 2
我用来测试这是否有效的脚本是:
console.log(process.argv[2]);
但是当我像node test.js 'Line 1\nLine2'
那样使用它时,它给我的输出是:
Line 1\nLine2
如何实现?
要解释发生了什么,请查看以下内容:
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>
在 ASCII table 中查找缓冲区值,您会发现:
10 0a 00001010 LF Line Feed
92 5c 01011100 \ \ backslash
110 6e 01101110 n n
因此,正如您所见,参数 '\n'
未被解释为换行符,而是按字面解释为 \
和 n
.
要解决此问题,使用 bash 您可以通过 $'<...>'
传递参数 expansion 强制转义序列被解释:
node test.js $'Line1\nLine2'
这将打印
Line1
Line2
按预期进入控制台。