Let’s see how to set up Visual Studio Code (VSCode) to work with Node.js. VSCode is probably the tool you use most frequently along with Node.js.
When working on a programming project, it’s normal that we use not just a simple text editor, but that we use an IDE. An IDE is a development environment; it is a “supercharged text editor” that incorporates more tools.
One of the most popular IDEs is the well-known VSCode. And we are in luck! Because they fit perfectly together, and are two great work companions.
Installing Visual Studio Code
Before we begin, make sure you have Visual Studio Code installed on your system. If you don’t know what that is, or if you haven’t installed it yet, check out this post.
What is it and how to install Visual Studio Code read more
Creating a Node.js script in VSCode
Creating a Node.js script with Visual Studio Code is very easy. Simply open VSCode in any folder where you want to work.
Now, right-click / create new item and create your file. For example, hello_world.js
.
Well, I already told you it would be very easy. Of course, you can create the file and folder structure you want. Or, you can use the integrated terminal in VSCode.
Running the File
Now comes the good part. To run our program, we can use the integrated terminal, and execute the following command:
node hello_world.js
You should see the output “Hello World from Node.js!” in the terminal. This is basically the same thing we did in the previous tutorial.
Oooooo,… now… you can also press F5 (which is the same as going to the top menu and choosing Run / Start Debugging)
A window like the following will appear, where VSCode is basically asking you “with what do you want to run this”. Select “Node.js” from the dropdown.
VSCode will take the file you have open and run it in Node.js. It will also show you the result in the integrated “Debug Console” window.
That is, you don’t have to use the command line to run node whatever.js
. You just have to press F5. If you like typing, then use the command line… I just press F5. 😊
Debugging Node.js applications in VSCode
Did you like it? Well, the best part is yet to come. VSCode provides debugging tools that can help you identify and fix errors in your Node.js code.
Let’s create a breakpoint. In your hello_world.js
file, click on the left margin next to the line of code where you want to set a breakpoint. This will create a red dot, indicating a breakpoint.
Now press F5 or select Run
> Start Debugging
to start debugging. The execution will stop at the breakpoints you have set.
While you are in debugging mode, you can inspect the values of the variables. Just hover over a variable to see its current value.
The debug console in VSCode allows you to execute JavaScript commands while in debugging mode. You can see the value of variables, execute functions, and more.
Now you have everything you need to start working properly with Node.JS and Visual Studio Code.