在终端中,Node.js文件出现“SyntaxError: unexpected identifier”的错误。

4
当我尝试在终端中使用node运行javascript文件时,出现“SyntaxError: unexpected identifier”的错误。
这是我的代码,保存为example.js。

console.log('hello world');

这是我的终端上正在发生的事情。

> Thoms-MacBook-Pro:desktop thomvaladez$ node
> console.log('hi');
hi
undefined
> node example.js
SyntaxError: Unexpected identifier
    at Object.exports.createScript (vm.js:44:10)
    at REPLServer.defaultEval (repl.js:117:23)
    at bound (domain.js:254:14)
    at REPLServer.runBound [as eval] (domain.js:267:12)
    at REPLServer.<anonymous> (repl.js:279:12)
    at REPLServer.emit (events.js:107:17)
    at REPLServer.Interface._onLine (readline.js:214:10)
    at REPLServer.Interface._line (readline.js:553:8)
    at REPLServer.Interface._ttyWrite (readline.js:830:14)
    at ReadStream.onkeypress (readline.js:109:10)

Node可以响应命令和代码,但我无法打开文件。有人知道可能出现的问题吗?

1个回答

5

大多数人在 node 会话之外运行该命令。

> Thoms-MacBook-Pro:desktop thomvaladez$ node example.js

如果您已经像之前所做的那样进入了节点会话,那么就像t3dodson建议的那样,在那个点上执行一个 require 命令即可。只需要在其前面加上 "./",这样它就能找到您的文件了。
> Thoms-MacBook-Pro:desktop thomvaladez$ node
> require ('./example.js')
> Hello World!

我猜你版本中的“node”是指“意外标识符”。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接