Run JavaScript in Visual Studio Code
Solution 1
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"
}
Solution 2
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.
Solution 3
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!
Solution 4
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.
Solution 5
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.
Related videos on Youtube
Nick Le Page
Developer mainly using C# and SQL Server, over 20 years experience stating out with C++ and Visual Basic. After this i spent a year using VB.net before moving on to C# for 10 years. I have been using SQL Server over my career. I love being a developer want to keep working in this area - so don't ask me why I am "still" a devloper Currently Working on an MVC project I describe myself as an mid-level in this area. In my spare time I am now learning WordPress. As I am not artistic this platform is allowing me to create great looking websites in little time. Studying for MVC and Azure certifications
Updated on April 27, 2022Comments
-
Nick Le Page over 1 year
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.
-
Jordan Running over 8 yearsThis sounds like an A/B problem. What is the problem you're actually trying to solve?
-
Kshitiz Sharma over 6 years@Chris He's referring to a software. VSCode is an editor
-
Lostfields almost 6 yearsI've just created a new Extension for VS Code just for this, try out "Node.JS REPL". marketplace.visualstudio.com/…
-
Mattl over 5 yearsThe easiest way to see the results is to goto View => Integrated Terminal and type: node <myfile>.js
-
Eric Burel over 2 yearsDid 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?
-
WasitShafi about 2 years@all Quokka, is consider to be one of the best way for running JavaScript/TypeScript codes, for more info please refer -> stackoverflow.com/questions/69456935/… - good luck all !!
-
-
Andrzej Rehmann about 8 yearsit works, but you have to modifie this file evertime you create a new file, this is not what OP is asking i think
-
Peter Dotchev over 7 yearsGood, but you need to press Shift+F5 at the end to stop the debugger
-
lebobbi over 7 yearsYou could also add a process.exit() to your code :D
-
AL - Divine over 6 yearsI 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"
-
Useless_Wizard over 5 yearsJust to add on to @TheBigShot point 4- If using Code Runners configuration guide link by adding an entry to 'code-runner.executorMap' inside VScode, the path value "\"C:\\Program Files\\nodejs\\node.exe\"" worked for me.
-
Roman about 5 yearsThis worked for me flawlessly! ( I had node installed and configured already)
-
Harry Theo almost 5 yearsquickest way possible to work for all your development folders! cheers!!
-
serg10 over 4 yearsOr
Control
+Option
+N
on OSX. -
Mark Wilbur over 4 yearsThe 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.
-
Robin Métral over 4 yearsAnd no need to install an extension with this solution! Does the debugger have the same features as Code Runner?
-
tenwest over 4 yearsI am not familiar with code runner, but, it behaves like any other debugger break points, function stepping in/out, variable/expression watching, etc
-
KhoPhi over 4 yearsThis makes the most sense
-
Jose Quijada over 4 yearsI'm relatively new to JavaScript development and VSCode, and by far this was the simplest solution.
-
vikramvi over 4 yearsBut this way you're doing debugging right and not running program. Until and unless there is no break point, it's like running program, do you mean the same ?
-
tenwest over 4 yearsWell, question wasn't asking to run a program, it asks to "execute javascript and display the results", this does both :)
-
Trapper Davis almost 4 yearsWorks perfectly! Exactly what I was looking for.
-
Gale over 3 yearsSuch a great answer!
-
MasterJoe over 3 years@Roman - I can run the code with this extension. But, how do I debug it ?
-
MasterJoe over 3 years@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.
-
Roman over 3 years@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"
-
NoobCoder over 3 yearsI am getting
Command 'Run Code' resulted in an error (command 'code-runner.run' not found)
-
tenwest about 3 years@MasterJoe this worked out of the box without any config 2 yrs ago, not sure about now. good luck! For what it's worth, I only used this on node code, never any browser interop
-
dcts about 3 yearsdont forget to restart VS code after installation! :)
-
Abhijit Chakra over 2 yearswhat is nodemon do i need to install it
-
davimdantas over 2 yearsNodemon 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
-
Abhijit Chakra over 2 yearswithout that i can simply write if i have already node node MyJSFileName.js
-
trainoasis over 2 yearsThat 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)
-
Savrige over 2 yearsNice! I just paste this in
File > Preferences > keyboard shortcuts
-
user48956 about 2 yearsWill that allow debugging and breakpoints?
-
user48956 about 2 yearsWill that allow debugging and breakpoints within VSCode?
-
user48956 about 2 yearsFor me, i) "Start debugging" is under "Run", ii) VSCode demands I select a (browser!) environment, and doesn't as a simple program.
-
user48956 about 2 yearsIt 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.
-
user48956 about 2 yearsIt doesn't seem to pay attention to breakpoints.
-
CrackerKSR about 2 yearsYes, 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
-
user48956 about 2 yearsI 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.
-
CrackerKSR about 2 yearsI think you should post a new question and explain there in detail so I would answer it properly.
-
CrackerKSR about 2 yearsCheckout August 2021 changelog . Now they are providing built in debugger code.visualstudio.com/updates/v1_60#_javascript-debugging
-
PhiLho over 1 yearAs a reminder, you don't need all these
\\
in your settings, in Windows, simple/
works too. -
InfiniteStack over 1 yearThanks for the answer :) This run js in vscode tutorial also pretty much explains same thing.