【问题标题】:Run simple js file using node使用节点运行简单的js文件
【发布时间】:2013-10-11 23:39:40
【问题描述】:

我正在使用节点 v0.10.20 和 OSX 10.8.5。

我创建了一个名为 variables.js 的简单 js 文件,您可以在下面看到:

var productName
var currentPrice
var totalCost
var productTax

productName = "cookies"
currentPrice = 3
productTax = currentPrice * .07
totalCost = currentPrice + productTax
console.log("Your " + productName + " cost $" + totalCost)

当我在节点 repl 或 chrome 中单独运行这些行时,它可以正常工作,并且输出是“您的 cookie 花费 3.21 美元”。

但是,当我从文件所在的目录运行命令“node variables.js”时,我收到以下错误消息:

/directorypath/variables.js:13
# create a javascript file (variables.js) that 
^
SyntaxError: Unexpected token ILLEGAL
 at Module._compile (module.js:439:25)
 at Object.Module._extensions..js (module.js:474:10)
 at Module.load (module.js:356:32)
 at Function.Module._load (module.js:312:12)
 at Function.Module.runMain (module.js:497:10)
 at startup (node.js:119:16)
 at node.js:901:3

我在这里做错了什么?

【问题讨论】:

  • 我将此代码复制到文件中并从终端运行(Ubuntu 12.04)。您的 cookie 成本为 3.21 美元 - 输出
  • 我已经在 Win 7、Node 0.10.5 上对其进行了测试,它的工作原理就像一个魅力
  • 在行尾加分号试试看..
  • @sriharsha 我用分号试过了,但还是不行。
  • 能否请您创建一个要点并在此处提供链接?

标签: javascript macos node.js terminal read-eval-print-loop


【解决方案1】:

您的错误在第 13 行,但您粘贴的 sn-p 只有 10 行代码。如果您希望我们能够尽可能地帮助您,您可能想发布整个脚本。

从错误中,我看到您正在使用 # 创建我认为是注释行的内容。即使您可以从终端运行 node.js 脚本,它仍然是 Javascript 而不是 bash。因此,您仍然使用// 来注释单行,或使用/* */ 来注释块。这里有两个例子:

// I'm a Javascript comment!

/* and all of this
text is as well!
*/

这是带有正确注释的代码:

var productName
var currentPrice
var totalCost
var productTax

productName = "cookies"
currentPrice = 3
productTax = currentPrice * .07
totalCost = currentPrice + productTax
console.log("Your " + productName + " cost $" + totalCost)
// Commented stuff would go here

【讨论】:

  • 谢谢 jmeas 就是这样。
猜你喜欢
  • 2016-06-06
  • 1970-01-01
  • 2016-06-29
  • 2016-11-17
  • 1970-01-01
  • 1970-01-01
  • 2018-02-19
  • 1970-01-01
  • 2018-03-20
相关资源
最近更新 更多