我使用bash脚本向节点应用程序发送参数,如下所示:
testString="\nhello\nthere"
node ./myNodeScript.js $testString当我在node程序中将其捕获为process.argv[2]之后使用testString时,问题就来了--而不是将\n字符扩展到换行符node逐字打印它们。我需要一种方法来告诉node将参数转换为javascript字符串,考虑到格式化字符。有没有办法解决这个问题?
发布于 2019-12-07 10:25:18
尽量避免混淆文字换行符和文字反斜杠,后面跟着文字n。
如果您希望传递的字符串具有换行符,则应忽略JavaScript字符串文字语法,仅将换行符作为换行符传递:
$ cat myNodeScript.js
console.log("Node was passed this: " + process.argv[2])
$ cat myBashScript
testString='
hello
there'
printf 'Bash passes this: %s\n' "$testString"
node myNodeScript.js "$testString"
$ bash myBashScript
Bash passes this:
hello
there
Node was passed this:
hello
there参数应包含数据(换行符),而脚本文件应包含代码(引号换行符或语言中适当的扩展\n )。当您确保不混淆代码和数据时,您可以轻松地处理同一字符串中的反斜杠-en和换行符,而不会有任何意外:
testString='
"\nhello\nthere" is JavaScript syntax for:
hello
there'在bash中,有一些方法可以在一行中表达这一点,使用\n表示换行符,\\n表示反斜杠-en,您只需确保它仍然是代码,并且不会意外地将其作为数据放入变量中。
发布于 2019-12-07 09:41:31
你能试试这个吗:
testString=$( printf "\nhello\nthere")
node ./myNodeScript.js "$testString"让我知道它是否有效?
https://stackoverflow.com/questions/59222209
复制相似问题