node.js 在 Visual Studio Code 中运行 JavaScript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31778413/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 19:12:21  来源:igfitidea点击:

Run JavaScript in Visual Studio Code

node.jsvisual-studio-code

提问by Nick Le Page

Is there a way to execute JavaScript and display the results using Visual Studio Code?

有没有办法执行 JavaScript 并使用Visual Studio Code显示结果?

For example, a script file containing:

例如,一个脚本文件包含:

console.log('hello world');

I assume that Node.js would be needed but can't work out how to do it?

我认为需要 Node.js 但不知道如何去做?

By Visual Studio CodeI mean the new Code Editor from Microsoft - Not code written using Visual Studio.

通过Visual Studio代码我的意思是,从微软新的代码编辑器-使用Visual Studio编写的代码没有。

采纳答案by canerbalci

This solution intends to run currently open file in node and show output in VSCode.

此解决方案旨在在节点中运行当前打开的文件并在 VSCode 中显示输出。

I had the same question and found newly introduced tasksuseful for this specific use case. It is a little hassle, but here is what I did:

我有同样的问题,发现新引入的tasks对这个特定用例很有用。这有点麻烦,但这是我所做的:

Create a .vscodedirectory in the root of you project and create a tasks.jsonfile in it. Add this task definition to the file:

.vscode在项目的根目录下创建一个目录并在其中创建一个tasks.json文件。将此任务定义添加到文件中:

{
    "version": "0.1.0",
    "command": "node",
    "isShellCommand": true,
    "args": [
        "--harmony"
    ],

    "tasks": [
        {
            "taskName": "runFile",
            "suppressTaskName": true,
            "showOutput": "always",
            "problemMatcher": "$jshint",
            "args": ["${file}"]
        }
    ]
}

Then you can: press F1 > type `run task` > enter > select `runFile` > enterto run your task, but I found it easier to add a custom key binding for opening tasks lists.

然后您可以: press F1 > type `run task` > enter > select `runFile` > enter运行您的任务,但我发现为打开任务列表添加自定义键绑定更容易。

To add the key binding, in VSCode UI menu, go 'Code' > 'Preferences' > 'Keyboard Shortcuts'. Add this to your keyboard shortcuts:

要添加键绑定,请在 VSCode UI 菜单中,转到“代码”>“首选项”>“键盘快捷键”。将此添加到您的键盘快捷键:

{
    "key": "cmd+r",
    "command": "workbench.action.tasks.runTask"
}

Of course you can select whatever you want as key combination.

当然,您可以选择任何您想要的组合键。

UPDATE:

更新:

Assuming you are running the JavaScript code to testit, you could mark your task as a testtask by setting its isTestCommandpropertyto trueand then you can bind a key to the workbench.action.tasks.testcommandfor a single-action invocation.

假设你正在运行的JavaScript代码来测试它,你可以标记你的任务作为检验其设置的任务isTestCommand属性true,然后你可以绑定一个关键workbench.action.tasks.test命令用于单动作调用。

In other words, your tasks.jsonfile would now contain:

换句话说,您的tasks.json文件现在将包含:

{
    "version": "0.1.0",
    "command": "node",
    "isShellCommand": true,
    "args": [
        "--harmony"
    ],

    "tasks": [
        {
            "taskName": "runFile",
            "isTestCommand": true,
            "suppressTaskName": true,
            "showOutput": "always",
            "problemMatcher": "$jshint",
            "args": ["${file}"]
        }
    ]
}

...and your keybindings.jsonfile would now contain:

...您的keybindings.json文件现在将包含:

{
    "key": "cmd+r",
    "command": "workbench.action.tasks.test"
}

回答by Jun Han

There is a much easier way to run JavaScript, no configuration needed:

有一种更简单的方式来运行 JavaScript,无需配置:

  1. Install the Code Runner Extension
  2. Open the JavaScript code file in Text Editor, then use shortcut Control+Alt+N(or ? Control+? Option+Non macOS), or press F1and then select/type Run Code, the code will run and the output will be shown in the Output Window.
  1. 安装代码运行器扩展
  2. 在文本编辑器中打开 JavaScript 代码文件,然后使用快捷键Control+ Alt+ N(或macOS 上的? Control+ ? Option+ N),或按F1然后选择/键入Run Code,代码将运行并且输出将显示在输出窗口中。

Besides, you could select part of the JavaScript code and run the code snippet. The extension also works with unsaved files, so you can just create a file, change it to Javascript and write code fast (for when you just need to try something quick). Very convenient!

此外,您可以选择部分 JavaScript 代码并运行代码片段。该扩展程序也适用于未保存的文件,因此您只需创建一个文件,将其更改为 Javascript 并快速编写代码(当您只需要快速尝试一些东西时)。很方便!

回答by tenwest

I am surprised this has not been mentioned yet:

我很惊讶这还没有被提及:

Simply open the .jsfile in question in VS Code, switch to the 'Debug Console' tab, hit the debug button in the left nav bar, and click the run icon (play button)!

只需.js在 VS Code 中打开有问题的文件,切换到“调试控制台”选项卡,点击左侧导航栏中的调试按钮,然后单击运行图标(播放按钮)!

Requires nodejs to be installed!

需要安装nodejs!

回答by coty h

The shortcut for the integrated terminal is ctrl+ `, then type node <filename>.

集成终端的快捷方式是ctrl+ `,然后键入node <filename>

Alternatively you can create a task. This is the only code in my tasks.json:

或者,您可以创建一个任务。这是我的 tasks.json 中唯一的代码:

{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "0.1.0",
"command": "node",
"isShellCommand": true,
"args": ["${file}"],
"showOutput": "always"
}

From here create a shortcut. This is my keybindings.json:

从这里创建一个快捷方式。这是我的 keybindings.json:

// Place your key bindings in this file to overwrite the defaults
[
{   "key": "cmd+r",
"command": "workbench.action.tasks.runTask"
},
{   "key": "cmd+e",
"command": "workbench.action.output.toggleOutput"
}
]

This will open 'run' in the Command Pallete, but you still have to type or select with the mouse the task you want to run, in this case node. The second shortcut toggles the output panel, there's already a shortcut for it but these keys are next to each other and easier to work with.

这将在命令面板中打开“运行”,但您仍然必须键入或用鼠标选择要运行的任务,在本例中为节点。第二个快捷方式切换输出面板,已经有一个快捷方式,但这些键彼此相邻,更易于使用。

回答by Vehbi

This is the quickest way for you in my opinion;

在我看来,这对你来说是最快的方式;

  • Open integrated terminal on visual studio code (View > Integrated Terminal)
  • type 'node filename.js'
  • press enter
  • 在 Visual Studio 代码上打开集成终端 ( View > Integrated Terminal)
  • 类型 'node filename.js'
  • 按回车

note: node setup required. (if you have a homebrew just type 'brew install node' on terminal)

注意:需要节点设置。(如果您有自制软件,只需在终端上输入“brew install node”)

note 2: homebrew and node highly recommended if you don't have already.

注意 2:如果您还没有自制软件和节点,强烈推荐。

have a nice day.

祝你今天过得愉快。

回答by Legend

I faced this exact problem, when i first start to use VS Codewith extension Code Runner

当我第一次开始使用带有扩展的VS Code时,我遇到了这个确切的问题Code Runner

The things you need to do is set the node.jspath in User Settings

您需要做的事情是在用户设置中设置node.js路径

You need to set the Pathas you Install it in your Windows Machine.

您需要在 Windows 机器中安装它时设置路径

For mine It was \"C:\\Program Files\\nodejs\\node.exe\"

对我来说是 \"C:\\Program Files\\nodejs\\node.exe\"

As I have a Space in my File Directory Name

因为我的文件目录名称中有一个空格

See this Imagebelow. I failed to run the code at firstcause i made a mistake in the Path Nameenter image description here

请参阅下面的这张图片。我一开始没能运行代码因为我在路径名中犯了一个错误在此处输入图片说明

Hope this will help you.

希望这会帮助你。

And ofcourse, Your Question helped me, as i was also come here to get a help to run JSin my VS CODE

当然,你的问题对我有帮助,因为我也是来这里寻求帮助JS在我的VS CODE 中运行的

回答by lebobbi

Well, to simply run the code and show the output on the console you can create a task and execute it, pretty much as @canerbalci mentions.

好吧,要简单地运行代码并在控制台上显示输出,您可以创建一个任务并执行它,就像@canerbalci 提到的那样。

The downside of this is that you will only get the output and thats it.

这样做的缺点是你只会得到输出,仅此而已。

What I really like to do is to be able to debug the code, lets say Im trying to solve a small algorithm or trying a new ES6 feature, and I run it and there is something fishy with it, I can debug it inside VSC.

我真正喜欢做的是能够调试代码,比如说我试图解决一个小算法或尝试一个新的 ES6 功能,我运行它并且它有一些可疑的东西,我可以在 VSC 中调试它。

So, instead of creating a task for it, I modified the .vscode/launch.json file in this directory as follows:

因此,我没有为其创建任务,而是修改了此目录中的 .vscode/launch.json 文件,如下所示:

{
"version": "0.2.0",
"configurations": [
    {
        "name": "Launch",
        "type": "node",
        "request": "launch",
        "program": "${file}",
        "stopOnEntry": true,
        "args": [],
        "cwd": "${fileDirname}",
        "runtimeExecutable": null,
        "runtimeArgs": [
            "--nolazy"
        ],
        "env": {
            "NODE_ENV": "development"
        },
        "externalConsole": false,
        "sourceMaps": false,
        "outDir": null
    }
]
}

What this does is that it will launch whichever file you are currently on, within the debugger of VSC. Its set to stop on start.

它的作用是在 VSC 的调试器中启动您当前所在的任何文件。它设置为在开始时停止。

To launch it, press F5 key, in the file you want to debug.

要启动它,请在要调试的文件中按 F5 键。

回答by CrackerKSR

Follow these steps in VS code.[performed in windows os]

在 VS 代码中执行这些步骤。 [在 windows 操作系统中执行]

  1. Create new file

  2. Write javascript codes in it

  3. Save file as filename.js

  4. Go to Debugging menu

  5. Click on Start debugging

  6. or simply press F5

  1. 创建新文件

  2. 在其中编写 javascript 代码

  3. 将文件另存为 filename.js

  4. 进入调试菜单

  5. 点击开始调试

  6. 或者直接按F5

screenshot of starting debugging

启动调试截图

screenshot of output of js code in terminal

终端js代码输出截图

回答by Aman Mishra

There is no need to set the environment for running the code on javascript,python,etc in visual studio code what you have to do is just install the Code Runner Extension and then just select the part of the code you want to run and hit the run button present on the upper right corner.

无需在 Visual Studio 代码中设置在 javascript、python 等上运行代码的环境,您只需安装 Code Runner Extension,然后只需选择要运行的代码部分并点击运行按钮出现在右上角。

回答by dmo

I used Node Exec, no config needed, builds the file that you are currently ending or what ever has been selected and outputs inside of VSCode.

我使用 Node Exec,无需配置,构建您当前正在结束的文件或已选择的文件并在 VSCode 中输出。

https://marketplace.visualstudio.com/items?itemName=miramac.vscode-exec-node

https://marketplace.visualstudio.com/items?itemName=miramac.vscode-exec-node

With a bit of config you can add Babel to do some on the fly transpiling too.

通过一些配置,您也可以添加 Babel 来进行一些即时转译。