ChatGPT解决这个技术问题 Extra ChatGPT

Run JavaScript in Visual Studio Code

Is there a way to execute JavaScript and display the results using 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?

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

This sounds like an A/B problem. What is the problem you're actually trying to solve?
@Chris He's referring to a software. VSCode is an editor
I've just created a new Extension for VS Code just for this, try out "Node.JS REPL". marketplace.visualstudio.com/…
The easiest way to see the results is to goto View => Integrated Terminal and type: node .js
Did you find any anwser that allow to run JavaScript from the browser perspective? Like you would do with a browser console on an empty HTML page?

C
Community

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

Install the Code Runner Extension Open the JavaScript code file in Text Editor, then use shortcut Control+Alt+N (or ⌃ Control+⌥ Option+N on macOS), or press F1 and then select/type Run Code, the code will run and the output will be shown in the Output Window.

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!

NodeJS is needed for this else it will not work.


I also needed 3- To install Node.js nodejs.org/en 4- Go to enviroment Variables and add "Node" with value: "C:\Program Files\nodejs\node.exe"
quickest way possible to work for all your development folders! cheers!!
I'm relatively new to JavaScript development and VSCode, and by far this was the simplest solution.
@MasterJoe2 - there is debug functionality in VS Code. I haven't done that in ages, to be honest. But try setting a breakpoint and click on "Run and Debug". If it doesn't work - Google around "how to debug JS in VS Code"
dont forget to restart VS code after installation! :)
A
Aliaksandr Sushkevich

I am surprised this has not been mentioned yet:

Simply open the .js file 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)!

Requires nodejs to be installed!


And no need to install an extension with this solution! Does the debugger have the same features as Code Runner?
This makes the most sense
Well, question wasn't asking to run a program, it asks to "execute javascript and display the results", this does both :)
@tenwest - don't you need a debug config first that uses node.js ? I currently have a debug config for chrome browser only. This opens up the chrome browser which I don't need because my code does not call any browser functions.
It does not work out of the box today. Some kind of debug configuration is required: Chrome, Edge, Node.js, VS Code Extension. None seem appropriate.
O
Olivier Dagenais

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

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

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

{
    "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` > enter to run your task, but I found it easier to add a custom key binding for opening tasks lists.

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

{
    "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 test it, you could mark your task as a test task by setting its isTestCommand property to true and then you can bind a key to the workbench.action.tasks.test command for a single-action invocation.

In other words, your tasks.json file would now contain:

{
    "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.json file would now contain:

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

The OP didn't say anything about having a project. It looks like they want to execute the single file currently open, which is a very reasonable thing to want from a text editor.
s
schrodingerscatcuriosity

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

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

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

have a nice day.


Thanks for the answer :) This run js in vscode tutorial also pretty much explains same thing.
If the js file contains client side script like sessionStorage, an error will be thrown in the terminal.
A
Aliaksandr Sushkevich

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

Alternatively you can create a task. This is the only code in my 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:

// 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.


C
CrackerKSR

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

Create new file Write javascript codes in it Save file as filename.js Go to Debugging menu Click on Start debugging or simply press F5

screenshot of starting debugging

screenshot of output of js code in terminal

Edit: Read this doc for latest configuration and features regarding JS for VSCode: https://code.visualstudio.com/docs/languages/javascript


For me, i) "Start debugging" is under "Run", ii) VSCode demands I select a (browser!) environment, and doesn't as a simple program.
Yes, I can see that in my current version of vscode. I tried to run js after your comment. it asks for browsers selection. It also shows Nodejs in the list and if you select Nodejs there then it will run the file and show the output on debug console without leaving the vscode or any further configs. Also when it asks for browser selection it also gives the option to install extensions which will make your task easier
I don't want to run it in a browser. If Inseect nodejs, compiler errors are not reported (at least, I can’t see the in the output - oddly, if I select the output windows, CTRL-A, CTRL-C, and paste in the editor, the errors are pasted. What the hey.
I think you should post a new question and explain there in detail so I would answer it properly.
Checkout August 2021 changelog . Now they are providing built in debugger code.visualstudio.com/updates/v1_60#_javascript-debugging
l
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.

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.

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

{
"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.

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


Good, but you need to press Shift+F5 at the end to stop the debugger
You could also add a process.exit() to your code :D
L
Legend

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

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

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

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

As I have a Space in my File Directory Name

https://i.stack.imgur.com/mDTrL.png

Hope this will help you.

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


As a reminder, you don't need all these \\ in your settings, in Windows, simple / works too.
M
Mark

This may now be the easiest, as of v1.32:

{
    "key": "ctrl+shift+t",
    "command": "workbench.action.terminal.sendSequence",
    "args": { "text": "node '${file}'\u000D" }
  }

Use your own keybinding.

See Release notes: sendSequence and variables.

With vscode v1.32 you can sendSequence to the terminal using variables like ${file}, which is the current file. If you want some other path there, replace ${file} with your pathname in the keybinding above.

The \u000D is a return so it will run immediately.

I added 's around the ${file} variable in case your file path has spaces in it, like c:Users\Some Directory\fileToRun


Nice! I just paste this in File > Preferences > keyboard shortcuts
S
Srijan Chaudhary

I would suggest you to use a simple and easy plugin called as Quokka which is very popular these days and helps you debug your code on the go. Quokka.js. One biggest advantage in using this plugin is that you save a lot of time to go on web browser and evaluate your code, with help of this you can see everything happening in VS code, which saves a lot of time.


d
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.

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.


d
davimdantas

Just install nodemon and run

nodemon your_file.js

on vs code terminal.


what is nodemon do i need to install it
Nodemon is a node package. If you have already a packahe manager like npm or yarn: Removed from NPM's Nodemon page: npm install -g nodemon And nodemon will be installed globally to your system path. You can also install nodemon as a development dependency: npm install --save-dev nodemon
without that i can simply write if i have already node node MyJSFileName.js
A
Abhijit Chakra

If you node installed on your machine

Just open the terminal in VSCODE and type node yourfile.js that's it


That is not a solution by itself. If you type "node" in terminal within VSCODE it opens interactive shell within terminal with "Welcome to Node.js v14.15.4." .. (at least on os x)
Will that allow debugging and breakpoints within VSCode?
A
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.


J
João Marcelo Brito

It's very simple, when you create a new file in VS Code and run it, if you already don't have a configuration file it creates one for you, the only thing you need to setup is the "program" value, and set it to the path of your main JS file, looks like this:

{
    "version": "0.1.0",
    // List of configurations. Add new configurations or edit existing ones.  
    // ONLY "node" and "mono" are supported, change "type" to switch.
    // ABSOLUTE paths are required for no folder workspaces.
    "configurations": [
        {
            // Name of configuration; appears in the launch configuration drop down menu.
            "name": "Launch",
            // Type of configuration. Possible values: "node", "mono".
            "type": "node",
            // ABSOLUTE path to the program.
            "program": "C:\\test.js", //HERE YOU PLACE THE MAIN JS FILE
            // Automatically stop program after launch.
            "stopOnEntry": false,
            // Command line arguments passed to the program.
            "args": [],
            // ABSOLUTE path to the working directory of the program being debugged. Default is the directory of the program.
            "cwd": "",
            // ABSOLUTE path to the runtime executable to be used. Default is the runtime executable on the PATH.
            "runtimeExecutable": null,
            // Optional arguments passed to the runtime executable.
            "runtimeArgs": [],
            // Environment variables passed to the program.
            "env": { },
            // Use JavaScript source maps (if they exist).
            "sourceMaps": false,
            // If JavaScript source maps are enabled, the generated code is expected in this directory.
            "outDir": null
        }, 
        {
            "name": "Attach",
            "type": "node",
            // TCP/IP address. Default is "localhost".
            "address": "localhost",
            // Port to attach to.
            "port": 5858,
            "sourceMaps": false
        }
    ]
}

it works, but you have to modifie this file evertime you create a new file, this is not what OP is asking i think
A
Alex Broadwin

Another option is to use the developer tools console within Visual Studio Code. Simply select "Toggle Developer Tools" from the help menu and then select the "Console" tab in the developer tools that pop up. From there you have the same dev tools REPL that you get in Chrome.


H
Harikrishnan

For windows: just change file association of .js file to node.exe

1) Take VSCode
2) Right click on the file in left pane
3) Click "Reveal in explorer" from context menu
4) Right click on the file -> Select "Open with" -> Select "Choose another program"
5) Check box "Always use this app to open .js file"
6) Click "More apps" -> "Look for another app in PC"
7) Navigate to node.js installation directory.(Default C:\Program Files\nodejs\node.exe"
8) Click "Open" and you can just see cmd flashing
9) Restart vscode and open the file -> Terminal Menu -> "Run active file".

I
Isak La Fleur

There are many ways to run javascript in Visual Studio Code.

If you use Node, then I recommend use the standard debugger in VSC.

I normally create a dummy file, like test.js where I do external tests.

In your folder where you have your code, you create a folder called ".vscode" and create a file called "launch.json"

In this file you paste the following and save. Now you have two options to test your code.

When you choose "Nodemon Test File" you need to put your code to test in test.js.

To install nodemon and more info on how to debug with nodemon in VSC I recommend to read this article, which explain in more detail the second part on the launch.json file and how to debug in ExpressJS.

{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "node",
            "request": "launch",
            "name": "Nodemon Test File",
            "runtimeExecutable": "nodemon",
            "program": "${workspaceFolder}/test.js",
            "restart": true,
            "console": "integratedTerminal",
            "internalConsoleOptions": "neverOpen"
        },
        {
            "type": "node",
            "request": "attach",
            "name": "Node: Nodemon",
            "processId": "${command:PickProcess}",
            "restart": true,
            "protocol": "inspector",
        },
    ]
}

J
Jiban Krisna Das

You have to set Node.js environment variable to run JavaScript code in VS code. Follow these settings and create path.

--Open Control Panel-> System -> Advanced System Settings -> Environment Variables --find variable PATH and add node.js folder path as value. Usually it is C:\Program Files Nodejs;. If variable doesn't exists, create it. --Restart your IDE or computer.

In case you are wondering the node executable should be in your C:\Program Files\nodejs folder.

In case you needed to check your PATH you can view it by right clicking the Computer in File Explorer or from the security settings in Control Panel. Once there select Advanced System Settings. A dialog will open with the Advanced tab selected. At the bottom is a button, Environment Variables.


E
Edwin Babu

Install nodemon with npm: npm install nodemon -g Init nodemon: npm init Open package.json and change it to: { "name": "JavaScript", "version": "1.0.0", "description": "", "main": "{filename}.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "nodemon {filename}.js" }, "keywords": [], "author": "", "license": "ISC" } Go to the terminal and write this command: npm start


Will that allow debugging and breakpoints?
K
Kasthuri Shravankumar

Use this file name tempCodeRunnerFile to run the java file without being saved

public class tempCodeRunnerFile{
    public static void main(String[] args) {
        System.out.println("aaaaaa");
    }
}

h
h3dkandi

Another way would be to open terminal ctrl+` execute node. Now you have a node REPL active. You can now send your file or selected text to terminal. In order to do that open VSCode command pallete (F1 or ctrl+shift+p) and execute >run selected text in active terminal or >run active file in active terminal.

If you need a clean REPL before executing your code you will have to restart the node REPL. This is done when in the Terminal with the node REPL ctrl+c ctrl+c to exit it and typing node to start new.

You could probably key bind the command pallete commands to whatever key you wish.

PS: node should be installed and in your path