简体   繁体   English

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

[英]Run simple js file using node

I am using node v0.10.20 and OSX 10.8.5. 我正在使用节点v0.10.20和OSX 10.8.5。

I created a simple js file called variables.js which you can see below: 我创建了一个简单的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)

When I run the lines individually in the node repl, or in chrome, it works correctly and the ouput is "Your cookies cost $3.21". 当我分别在节点repl或chrome中运行这些行时,它可以正常工作,输出是“您的cookie花费$ 3.21”。

However, when I run the command "node variables.js" from the directory that the file is located in I get the following error message: 但是,当我从文件所在的目录运行命令“ 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

What am I doing incorrectly here? 我在这里做错了什么?

Your error is on line 13, yet the snippet you pasted only has 10 lines of code. 您的错误在第13行,但是您粘贴的代码段只有10行代码。 You might want to post the whole script if you want us to be able to help ya as best as we can. 如果希望我们能够为您提供尽可能多的帮助,则可能需要发布整个脚本。

From the error, I'm seeing that you're using # to create what I think is a commented line. 从错误中,我看到您正在使用#来创建我认为是注释行的内容。 Even though you can run node.js scripts from the terminal, it's still Javascript and not bash. 即使可以从终端运行node.js脚本,它仍然是Javascript而不是bash。 Accordingly, you still use // to comment a single line, or /* */ for comment blocks. 因此,您仍然使用//注释一行,或使用/* */注释块。 Here are two examples: 这是两个示例:

// I'm a Javascript comment!

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

And this is your code with a proper comment: 这是带有适当注释的代码:

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