简体   繁体   中英

Run simple js file using node

I am using node v0.10.20 and OSX 10.8.5.

I created a simple js file called variables.js which you can see below:

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".

However, when I run the command "node variables.js" from the directory that the file is located in I get the following error message:

/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. 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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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