JavaScript函数不会在Visual Studio代码中将任何内容记录到终端

问题描述 投票:2回答:2

我试过这样运行函数:

function helloWorld() {
    console.log("Hello World!");
}

helloWorld()

enter image description here

我试图以这种方式运行该功能:

function helloWorld() {
    let text = "Hello World!";
    console.log(text);
}

helloWorld()

enter image description here

但无论如何,没有任何东西被记录到终端。第一种方法是给我一个语法错误:

syntax error near unexpected token 'helloWorld'

任何人都可以帮助我理解为什么我无法在Visual Studio Code中的终端中运行简单的功能?

谢谢

编辑:将helloWorld()添加到文件的底部。

该文件位于我的桌面上。我试着进入:

myName-MBP:~ myName$ node </desktop/index.js>

这回来了:

bash: syntax error near unexpected token 'newline'

enter image description here

编辑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

javascript function terminal visual-studio-code
2个回答
1
投票

正如arfat's answer所述,您可以在终端中使用Node.js运行代码:$ node /desktop/index.js

或者,您可以安装vscode扩展Code Runner。这样可以通过键盘快捷键轻松查看OUTPUT选项卡中的控制台日志:Ctrl+Alt+N


3
投票

你有nodejs安装?如果是,则可以键入node <filepath>,其中filepath是文件的路径并执行JavaScript文件。

假设您的文件名为script.js,然后尝试在终端输入node script.js,看看是否有帮助。另外,请确保您的shell位于当前目录中。

JavaScript无法直接在bash shell中执行。你需要nodejs来执行它。

© www.soinside.com 2019 - 2024. All rights reserved.