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

Run simple js file using node

本文关键字:js 文件 简单 运行 节点      更新时间:2023-09-26

我正在使用节点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 美元"。

但是,当我从文件所在的目录运行命令"节点变量.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