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.
There is a much easier way to run JavaScript, no configuration needed:
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 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!
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"
}
This is the quickest way for you in my opinion;
View > Integrated Terminal
)'node filename.js'
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.
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.
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
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.
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
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
This may now be the easiest, as of v1.32:<\/i>
{
"key": "ctrl+shift+t",
"command": "workbench.action.terminal.sendSequence",
"args": { "text": "node '${file}'\u000D" }
}
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 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.
Just install nodemon and run
nodemon your_file.js
on vs code terminal.
If you node installed on your machine
Just open the terminal in VSCODE
and type node yourfile.js
that's it
无需在 Visual Studio 代码中设置在 javascript、python 等上运行代码的环境,您只需安装 Code Runner Extension,然后只需选择要运行的代码部分并点击右上角的运行按钮。
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
}
]
}
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.
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 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 thisarticle , 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",
},
]
}
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.
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
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");
}
}
G:\nodejs\node.exe
MyTestSpace
-> create a new file call eg: test.js
console.log('-----test-----');
in test.js
Run and Debug
panel (ctrl+shift+d) > Run drop down list
at the top > Add Config (MyTestSpace)
> a launch.json
should be auto generated for you Node.js: Launch Program
> auto complete config fill in > rename the program
to the path where your test.js
locate
launch.json
should look something like this:: { "version": "0.2.0", "configurations": [ { "type": "node", "request": "launch", "name": "Launch Program", "program": "${workspaceFolder}/test.js", }, ], }
Run drop down list
> select Launch Program (MyTestSpace)
> click the Run
button Debug Console
should see the following:: G:\nodejs\node.exe.\test.js -----test-----
main.html
file, with a <script>
tag refer to the test.js
Run drop down list
> add config > select Chrome > auto complete launch.json
> change path to main.html
{ "type": "chrome", "request": "launch", "name": "Open test.html", "file": "h:\\Book\\debug\\LXPI\\OEBPS\\lib_new2\\libNt\\crossFileHtse\\build_HighlightTypeset_ReadHtse\\test.html", },
chrome launch config
> Run > html is opened up in your browser & console log printed 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
Simply search "Mozilla javascript reference" on google. Open the first link (developer.mozilla) and then open any link in that page. It provides "Try it" example codes which you can delete and write and test your own code there. Simple. No need for VS-Code:-)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.