繁体   English   中英

使用节点运行简单的js文件

[英]Run simple js file using node

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

我创建了一个简单的js文件,名为variables.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

我在这里做错了什么?

您的错误在第13行,但是您粘贴的代码段只有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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM