[node.js] 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 question is related to node.js visual-studio-code

The answer is


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.


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.


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.


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.


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",
        },
    ]
}

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

See this Image below. I failed to run the code at first cause i made a mistake in the Path Name enter 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 JS in my VS CODE


Just install nodemon and run

nodemon your_file.js

on vs code terminal.


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


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

  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

screenshot of starting debugging

screenshot of output of js code in terminal


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.


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!


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.


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

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

  1. Install the Code Runner Extension
  2. 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!


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.


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
        }
    ]
}

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