我试过这样运行函数:
function helloWorld() {
console.log("Hello World!");
}
helloWorld()
我试图以这种方式运行该功能:
function helloWorld() {
let text = "Hello World!";
console.log(text);
}
helloWorld()
但无论如何,没有任何东西被记录到终端。第一种方法是给我一个语法错误:
syntax error near unexpected token 'helloWorld'
任何人都可以帮助我理解为什么我无法在Visual Studio Code中的终端中运行简单的功能?
谢谢
编辑:将helloWorld()
添加到文件的底部。
该文件位于我的桌面上。我试着进入:
myName-MBP:~ myName$ node </desktop/index.js>
这回来了:
bash: syntax error near unexpected token 'newline'
编辑2:问题最初解决了,但后来我在运行node
命令时开始出现此错误:
internal/modules/cjs/loader.js:582
throw err;
^
Error: Cannot find module 'C:\Users\User\Desktop\NodeJsProject\app.js'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:580:15)
at Function.Module._load (internal/modules/cjs/loader.js:506:25)
at Function.Module.runMain (internal/modules/cjs/loader.js:741:12)
at startup (internal/bootstrap/node.js:285:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:739:3)
正如this article所述。我已经在我的系统上安装了node
。
帮助我解决这个问题的原因是在桌面上创建一个新文件夹,将.js文件放在该文件夹中,在VS Code中打开该文件夹,然后在终端中键入node index.js
。
正如arfat's answer所述,您可以在终端中使用Node.js运行代码:$ node /desktop/index.js
。
或者,您可以安装vscode扩展Code Runner。这样可以通过键盘快捷键轻松查看OUTPUT
选项卡中的控制台日志:Ctrl+Alt+N
。
你有nodejs
安装?如果是,则可以键入node <filepath>
,其中filepath
是文件的路径并执行JavaScript文件。
假设您的文件名为script.js
,然后尝试在终端输入node script.js
,看看是否有帮助。另外,请确保您的shell位于当前目录中。
JavaScript无法直接在bash shell中执行。你需要nodejs
来执行它。