Run JavaScript in Visual Studio Code

586,474

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:

  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!

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.

Share:
586,474

Related videos on Youtube

Nick Le Page
Author by

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, 2022

Comments

  • Nick Le Page
    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
      Jordan Running over 8 years
      This sounds like an A/B problem. What is the problem you're actually trying to solve?
    • Kshitiz Sharma
      Kshitiz Sharma over 6 years
      @Chris He's referring to a software. VSCode is an editor
    • Lostfields
      Lostfields almost 6 years
      I've just created a new Extension for VS Code just for this, try out "Node.JS REPL". marketplace.visualstudio.com/…
    • Mattl
      Mattl over 5 years
      The easiest way to see the results is to goto View => Integrated Terminal and type: node <myfile>.js
    • Eric Burel
      Eric Burel over 2 years
      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?
    • WasitShafi
      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
    Andrzej Rehmann about 8 years
    it 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
    Peter Dotchev over 7 years
    Good, but you need to press Shift+F5 at the end to stop the debugger
  • lebobbi
    lebobbi over 7 years
    You could also add a process.exit() to your code :D
  • AL - Divine
    AL - Divine over 6 years
    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"
  • Useless_Wizard
    Useless_Wizard over 5 years
    Just 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
    Roman about 5 years
    This worked for me flawlessly! ( I had node installed and configured already)
  • Harry Theo
    Harry Theo almost 5 years
    quickest way possible to work for all your development folders! cheers!!
  • serg10
    serg10 over 4 years
    Or Control + Option + N on OSX.
  • Mark Wilbur
    Mark Wilbur over 4 years
    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.
  • Robin Métral
    Robin Métral over 4 years
    And no need to install an extension with this solution! Does the debugger have the same features as Code Runner?
  • tenwest
    tenwest over 4 years
    I am not familiar with code runner, but, it behaves like any other debugger break points, function stepping in/out, variable/expression watching, etc
  • KhoPhi
    KhoPhi over 4 years
    This makes the most sense
  • Jose Quijada
    Jose Quijada over 4 years
    I'm relatively new to JavaScript development and VSCode, and by far this was the simplest solution.
  • vikramvi
    vikramvi over 4 years
    But 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
    tenwest over 4 years
    Well, question wasn't asking to run a program, it asks to "execute javascript and display the results", this does both :)
  • Trapper Davis
    Trapper Davis almost 4 years
    Works perfectly! Exactly what I was looking for.
  • Gale
    Gale over 3 years
    Such a great answer!
  • MasterJoe
    MasterJoe over 3 years
    @Roman - I can run the code with this extension. But, how do I debug it ?
  • MasterJoe
    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
    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
    NoobCoder over 3 years
    I am getting Command 'Run Code' resulted in an error (command 'code-runner.run' not found)
  • tenwest
    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
    dcts about 3 years
    dont forget to restart VS code after installation! :)
  • Abhijit Chakra
    Abhijit Chakra over 2 years
    what is nodemon do i need to install it
  • davimdantas
    davimdantas over 2 years
    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
  • Abhijit Chakra
    Abhijit Chakra over 2 years
    without that i can simply write if i have already node node MyJSFileName.js
  • trainoasis
    trainoasis over 2 years
    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)
  • Savrige
    Savrige over 2 years
    Nice! I just paste this in File > Preferences > keyboard shortcuts
  • user48956
    user48956 about 2 years
    Will that allow debugging and breakpoints?
  • user48956
    user48956 about 2 years
    Will that allow debugging and breakpoints within VSCode?
  • user48956
    user48956 about 2 years
    For me, i) "Start debugging" is under "Run", ii) VSCode demands I select a (browser!) environment, and doesn't as a simple program.
  • user48956
    user48956 about 2 years
    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.
  • user48956
    user48956 about 2 years
    It doesn't seem to pay attention to breakpoints.
  • CrackerKSR
    CrackerKSR about 2 years
    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
  • user48956
    user48956 about 2 years
    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.
  • CrackerKSR
    CrackerKSR about 2 years
    I think you should post a new question and explain there in detail so I would answer it properly.
  • CrackerKSR
    CrackerKSR about 2 years
    Checkout August 2021 changelog . Now they are providing built in debugger code.visualstudio.com/updates/v1_60#_javascript-debugging
  • PhiLho
    PhiLho over 1 year
    As a reminder, you don't need all these \\ in your settings, in Windows, simple / works too.
  • InfiniteStack
    InfiniteStack over 1 year
    Thanks for the answer :) This run js in vscode tutorial also pretty much explains same thing.