Node.js 语法错误 : Unexpected end of input

标签 node.js bash shell

我在shell脚本中编写了一个函数:

function nodee() {
    node -e "console.log((function() { $@ })());"
}
export -f nodee

这样调用它:

nodee "var a = 1, b = 2;" "return a + b;"

然后我得到一个错误:

[eval]:1
console.log((function() { var a = 1, b = 2;

SyntaxError: Unexpected end of input
    at Object.<anonymous> ([eval]-wrapper:6:22)
    at Module._compile (module.js:456:26)
    at evalScript (node.js:532:25)
    at startup (node.js:80:7)
    at node.js:902:3

但这没关系:

nodee "var a = 1, b = 2; return a + b;"

最后,我发现像这样声明 nodee 可以解决问题:

function nodee() {
    node -e "console.log((function() { `echo $@` })());"
}
export -f nodee

但是下面两行打印出相同的结果:

echo "console.log((function() { `echo $@` })());"
echo "console.log((function() { $@ })());"

那么,问题是这两行有什么区别?

node -e "console.log((function() { `echo $@` })());"
node -e "console.log((function() { $@ })());"

Mac OS X:10.9.2 和 Node.js:0.10.26

提前致谢!

最佳答案

$@ 在引号中很神奇,会产生多个参数:

$ set -- foo bar baz
$ printf "Argument: %s\n" "Hello $@ world"
Argument: Hello foo
Argument: bar
Argument: baz world

由于node只需要一个参数,所以它会出错。

您想要的是 $*,它连接参数而不创建多个参数:

$ printf "Argument: %s\n" "Hello $* world"
Argument: Hello foo bar baz world

`echo $@` 基本上是一种做同样事情的黑客方法 - 将多个参数连接到一个字符串中 - 除非它会在许多边缘情况下中断,例如嵌入换行或通配符:

$ set -- "var = 2 * 3;"
$ printf "Argument: %s\n" "Hello $* world"
Argument: Hello var = 2 * 3; world

$ printf "Argument: %s\n" "Hello `echo $@` world"
Argument: Hello var = 2 a.class a.java a.out barcode.png [...] 3; world

关于Node.js 语法错误 : Unexpected end of input,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23500098/

相关文章:

Node.js/Mongoose/按顺序排序并显示

javascript - Nodejs&Formidable, 上传图片

regex - inotifywait 根据修改的文件类型运行命令

linux - shell脚本if语句问题

node.js - 按顺序运行大量的 Promise

node.js - Node.js 上的 starttls > 0.4.0

bash:为什么我不能在后台 shell 中为 SIGINT 设置陷阱?

linux - 如何在linux上监控各种进程

linux - 启动时运行脚本,重新启动时运行其他脚本

shell - 在Shell脚本中的ssh session 中评估和分配变量