Как запустить javascript код в vs code
Перейти к содержимому

Как запустить javascript код в vs code

  • автор:

How To Run JavaScript In Visual Studio Code

Visual Studio Code will use NodeJS to run JavaScript . So, first make sure to install NodeJS.

If you haven’t done it already download NodeJS from official site and install it to C:\nodejs (or similar directory, by selecting it during installation.) Make sure to memorize it, you will need it in a later step.

index.js in Visual Studio Code? —>

To run JavaScript in VSCode , you have several options.

One way to run JavaScript is by using VSCode ‘s LiveSever extension.

Follow these steps to get started:

  1. Install NodeJS on your system. ( Download NodeJS here .)
  2. If you are on Windows, add the location of your new NodeJS installation ( C:\nodejs for example) to PATH variable in Environment Variables .
  3. Run node —version in Terminal (or cmd.exe ) to make sure NodeJS is installed.

How to run JavaScript on localhost in Visual Studio Code (using LiveServer extension)

To setup your computer for web development, you will want to run JavaScript in your browser on localhost address. You can’t do that without NodeJS. We’ve just done that in previous step!

If you want to run JavaScript in your browser for web development, one way to set it up is via VSCode’s LiveServer extension. NodeJS is the actual program that runs your JavaScript. But LiveServer puts everything together for you.

With NodeJS installed, go to VSCode’s Extensions button, and search for LiveServer . Click on first search result and then click on Install LiveServer button.

To run JS on localhost in your Chrome or Firefox browser in Visual Studio Code you can start it with LiveServer extension :

After installing LiveServer you should have new «Go Live» button added to your VSCode status bar. Simply open your JavaScript project, add index.html and click Go Live button.

How to select which browser you want to run JavaScript in via LiveServer extension

When you click Go Live button, your JS app should launch in browser.

But how to choose which browser should open by default?

Next to Install button, go to Live Server’s settings gear button and choose Extension Settings .

On the settings page that opens, click on settings.json icon in upper right corner:

You can also get to this page by going to File -> Preferences -> Settings

(Or pressing Ctrl + , keyboard shortcut.)

Now with settings.json file open, add the following settings to your Live Server config:

So that now part of your settings.json file will look something like:

This will setup Live Server for opening your HTML file in chrome browser.

But you can also specify other values like firefox or safari for example.

If you’re on Windows you must add NodeJS to Environment Variables

This is important because it allows you to run NodeJS executable from any location on your hard drive, not just from its installation folder.

This is also what will enable VSCode to run JavaScript.

Some NodeJS installers will do this step for you, but it’s still best to make sure.

Go to Start button and type «Environment Variables»

Hit Enter and on next screen, follow these steps:

How to find «Environment Variables» and change PATH variable

Just to round up, in order to add C:\nodejs to PATH variable follow these steps:

  1. Click on Start button and just start typing «environment variables»
  2. Hit enter and on next screen click «Environment Variables» button
  3. On next window go to second box below («System Variables») and locate PATH variable
  4. Click on PATH variable to select it, and click «Edit. » button
  5. Click «Add» button and type C:\nodejs (or location where you actually installed Node)
  6. Click Ok button on each window as they close to confirm changes.
  7. That’s it! You’ve just added NodeJS installation folder to PATH

JavaScript does not run in Visual Studio Code editor itself, it is executed by NodeJS.

How to run JavaScript in Visual Studio Code

VS code is a text editor made by Microsoft and it is an open-source project. It has extensions and other features for debugging your javascript, which we will talk about in this post.

Installing vs code is easy, just visit vs code’s website and get the installer here: https://code.visualstudio.com/download

After you install vs code, you can create a new file (ctrl+n), name it something like «test». For this example we use test.js. You can also click on the folder icon and add the javascript there:

Are you Using VS code on your laptop or pc?

Exit fullscreen mode

After that’s done, put «console.log(‘hello world’)» in your javascript file! The console will pop up automatically when you click on the vs code’s running tab. In the vs code window, you’ll see something that says «Attach». Once you click on attach, a new vs code window will pop up and it will run your javascript file!

VS code also has extensions so you can debug your javascript better. Such as debugging multiple browsers at once or have a debugger tell vs code what to do when an exception is thrown.

Creating a Web Server in VS Code

Now that’s over with let’s get into how to create a web server with vs code! You’re going to want to drag and drop 2 files into vs code they are index.html and app.js. Open vs code’s «settings» by right-clicking on the file name.

Click on settings, then go to «ignored files» and add «.git»:

Then you want to click on «open vs editor window here», so vs code knows how to run your program:

Now you can edit your index.html file! You can also see that vs code has already added some stuff for us since it opens automatically:(but we’re not going to use this yet)

VS code will try to help you out with minimal errors by telling you that vs code has attached itself to your app.js file, it also tells you that vs code’s debugger is running on port 9229.

To run vs code, click on the vs code running tab and click «F5» or hit «F5». To debug HTML files, go under Tools/HTML sub vs sub ctrl+p sub debug or hit F5 :

Name already in use

vscode-docs / docs / nodejs / nodejs-tutorial.md

  • Go to file T
  • Go to line L
  • Copy path
  • Copy permalink
  • Open with Desktop
  • View raw
  • Copy raw contents Copy raw contents

Copy raw contents

Copy raw contents

Node.js tutorial in Visual Studio Code

Node.js is a platform for building fast and scalable server applications using JavaScript. Node.js is the runtime and npm is the Package Manager for Node.js modules.

Visual Studio Code has support for the JavaScript and TypeScript languages out-of-the-box as well as Node.js debugging. However, to run a Node.js application, you will need to install the Node.js runtime on your machine.

To get started in this walkthrough, install Node.js for your platform. The Node Package Manager is included in the Node.js distribution. You’ll need to open a new terminal (command prompt) for the node and npm command-line tools to be on your PATH.

To test that you have Node.js installed correctly on your computer, open a new terminal and type node —version and you should see the current Node.js version installed.

Linux: There are specific Node.js packages available for the various flavors of Linux. See Installing Node.js via package manager to find the Node.js package and installation instructions tailored to your version of Linux.

Windows Subsystem for Linux: If you are on Windows, WSL is a great way to do Node.js development. You can run Linux distributions on Windows and install Node.js into the Linux environment. When coupled with the WSL extension, you get full VS Code editing and debugging support while running in the context of WSL. To learn more, go to Developing in WSL or try the Working in WSL tutorial.

Let’s get started by creating the simplest Node.js application, «Hello World».

Create an empty folder called «hello», navigate into and open VS Code:

Tip: You can open files or folders directly from the command line. The period ‘.’ refers to the current folder, therefore VS Code will start and open the Hello folder.

From the File Explorer toolbar, press the New File button:

File Explorer New File

and name the file app.js :

File Explorer app.js

By using the .js file extension, VS Code interprets this file as JavaScript and will evaluate the contents with the JavaScript language service. Refer to the VS Code JavaScript language topic to learn more about JavaScript support.

Create a simple string variable in app.js and send the contents of the string to the console:

Note that when you typed console. IntelliSense on the console object was automatically presented to you.

console IntelliSense

Also notice that VS Code knows that msg is a string based on the initialization to ‘Hello World’ . If you type msg. you’ll see IntelliSense showing all of the string functions available on msg .

string IntelliSense

After experimenting with IntelliSense, revert any extra changes from the source code example above and save the file ( kb(workbench.action.files.save) ).

Running Hello World

It’s simple to run app.js with Node.js. From a terminal, just type:

You should see «Hello World» output to the terminal and then Node.js returns.

VS Code has an integrated terminal which you can use to run shell commands. You can run Node.js directly from there and avoid switching out of VS Code while running command-line tools.

View > Terminal ( kb(workbench.action.terminal.toggleTerminal) with the backtick character) will open the integrated terminal and you can run node app.js there:

integrated terminal

For this walkthrough, you can use either an external terminal or the VS Code integrated terminal for running the command-line tools.

Debugging Hello World

As mentioned in the introduction, VS Code ships with a debugger for Node.js applications. Let’s try debugging our simple Hello World application.

To set a breakpoint in app.js , put the editor cursor on the first line and press kb(editor.debug.action.toggleBreakpoint) or click in the editor left gutter next to the line numbers. A red circle will appear in the gutter.

app.js breakpoint set

To start debugging, select the Run and Debug view in the Activity Bar:

You can now click Debug toolbar green arrow or press kb(workbench.action.debug.start) to launch and debug «Hello World». Your breakpoint will be hit and you can view and step through the simple application. Notice that VS Code displays a different colored Status Bar to indicate it is in Debug mode and the DEBUG CONSOLE is displayed.

hello world debugging

Now that you’ve seen VS Code in action with «Hello World», the next section shows using VS Code with a full-stack Node.js web app.

Note: We’re done with the «Hello World» example so navigate out of that folder before you create an Express app. You can delete the «Hello» folder if you want as it is not required for the rest of the walkthrough.

An Express application

Express is a very popular application framework for building and running Node.js applications. You can scaffold (create) a new Express application using the Express Generator tool. The Express Generator is shipped as an npm module and installed by using the npm command-line tool npm .

Tip: To test that you’ve got npm correctly installed on your computer, type npm —help from a terminal and you should see the usage documentation.

Install the Express Generator by running the following from a terminal:

The -g switch installs the Express Generator globally on your machine so you can run it from anywhere.

We can now scaffold a new Express application called myExpressApp by running:

This creates a new folder called myExpressApp with the contents of your application. The —view pug parameters tell the generator to use the pug template engine.

To install all of the application’s dependencies (again shipped as npm modules), go to the new folder and execute npm install :

At this point, we should test that our application runs. The generated Express application has a package.json file which includes a start script to run node ./bin/www . This will start the Node.js application running.

From a terminal in the Express application folder, run:

The Node.js web server will start and you can browse to http://localhost:3000 to see the running application.

Your first Node Express App

Great code editing

Close the browser and from a terminal in the myExpressApp folder, stop the Node.js server by pressing kbstyle(CTRL+C) .

Now launch VS Code:

Note: If you’ve been using the VS Code integrated terminal to install the Express generator and scaffold the app, you can open the myExpressApp folder from your running VS Code instance with the File > Open Folder command.

The Node.js and Express documentation does a great job explaining how to build rich applications using the platform and framework. Visual Studio Code will make you more productive in developing these types of applications by providing great code editing and navigation experiences.

Open the file app.js and hover over the Node.js global object __dirname . Notice how VS Code understands that __dirname is a string. Even more interesting, you can get full IntelliSense against the Node.js framework. For example, you can require http and get full IntelliSense against the http class as you type in Visual Studio Code.

http IntelliSense

VS Code uses TypeScript type declaration (typings) files (for example node.d.ts ) to provide metadata to VS Code about the JavaScript based frameworks you are consuming in your application. Type declaration files are written in TypeScript so they can express the data types of parameters and functions, allowing VS Code to provide a rich IntelliSense experience. Thanks to a feature called Automatic Type Acquisition , you do not have to worry about downloading these type declaration files, VS Code will install them automatically for you.

You can also write code that references modules in other files. For example, in app.js we require the ./routes/index module, which exports an Express.Router class. If you bring up IntelliSense on index , you can see the shape of the Router class.

Express.Router IntelliSense

Debug your Express app

You will need to create a debugger configuration file launch.json for your Express application. Click on Run and Debug in the Activity Bar ( kb(workbench.view.debug) ) and then select the create a launch.json file link to create a default launch.json file. Select the Node.js environment by ensuring that the type property in configurations is set to «node» . When the file is first created, VS Code will look in package.json for a start script and will use that value as the program (which in this case is «$\\bin\\www ) for the Launch Program configuration.

Save the new file and make sure Launch Program is selected in the configuration dropdown at the top of the Run and Debug view. Open app.js and set a breakpoint near the top of the file where the Express app object is created by clicking in the gutter to the left of the line number. Press kb(workbench.action.debug.start) to start debugging the application. VS Code will start the server in a new terminal and hit the breakpoint we set. From there you can inspect variables, create watches, and step through your code.

Debug session

Deploy your application

If you’d like to learn how to deploy your web application, check out the Deploying Applications to Azure tutorials where we show how to run your website in Azure.

There is much more to explore with Visual Studio Code, please try the following topics:

Using Node.js with Visual Studio Code [Step-by-Step]

Knowing how to use Node.js with Visual Studio Code is easy. All you do is install your preferred Node.js version and Visual Studio Code for your operating system or kernel. Next, create or open a .js file with Visual Studio Code.

But if you want to be more comfortable building Node.js applications, you need to go an extra step in installing and customizing the tools for effective development.

This tutorial teaches you how to use Node.js with Visual Studio Code. It walks you through Node.js and Visual Studio Code installation, navigating the editor interface and settings, and using shortcuts and themes. Lastly, you will test your skills by building a simple web server.

This section focuses on installing Node.js and Visual Studio Code on your operating system.

Step-1: Download and Install Node.js

We will download and install Node.js on our Ubuntu server. Let’s start by inspecting what the Linux repositories have for us.

Install the default (lower) version of Node.js if you are comfortable with it. Otherwise follow these steps to install a higher version for your operating system.

For Windows, click the link the LTS or current version and answer prompts to install Node.js on your system. For Linux and MacOS, you should proceed with the following steps to install your preferred Node.js version.

Below the link to the current version, click on Other Downloads.

Using Node.js with Visual Studio Code [Step-by-Step]

Scroll down the page to the links section. Choose the one written Installing Node.js via package manager.

Using Node.js with Visual Studio Code [Step-by-Step]

Choose the installer for your operating system/kernel type. I am picking the option called Debian and Ubuntu based Linux distributions because I am installing Node.js on Ubuntu 20.04 machine.

Using Node.js with Visual Studio Code [Step-by-Step]

I then click on the link leading me to Node.js binary distributions repository.

Using Node.js with Visual Studio Code [Step-by-Step]

Scroll down the page and copy your download command on the target version section. I am picking version 18 (v18.x) for Ubuntu.

Using Node.js with Visual Studio Code [Step-by-Step]

Return to the terminal and run the command.

If curl is not found, install it first.

Then retry installing Node.js libraries.

Next, install the picked Node.js version.

Using Node.js with Visual Studio Code [Step-by-Step]

Lastly, confirm your installation by checking the Node.js version.

Likewise, you can confirm npm installation (automatically installed with Node.js) by checking its version.

Using Node.js with Visual Studio Code [Step-by-Step]

Now that you have installed Node.js, let me show how to install Visual Studio Code on your system.

Step-2: Download and Install Visual Studio Code

Installing on Windows and MacOS

Click on Download for Windows button. Likewise the website is intelligent enough to detect you have visited it with a Mac machine.

Using Node.js with Visual Studio Code [Step-by-Step]

Visual Studio Code starts downloading once the download is complete. Answer the straightforward prompts to install the editor on your system.

Installing on Linux

Select the installation package for your distro type. I am choosing .deb because it suits my Ubuntu distribution.

Using Node.js with Visual Studio Code [Step-by-Step]

Visual Studio Code is downloaded into your Downloads folder.

Using Node.js with Visual Studio Code [Step-by-Step]

Navigate to the Downloads folder to confirm the successful download.

Copy the downloaded file’s name and install Visual studio using dpkg .

Using Node.js with Visual Studio Code [Step-by-Step]

Now, Visual Studio Code should be available under the installed applications.

Using Node.js with Visual Studio Code [Step-by-Step]

Now that we have installed both Node.js and Visual Studio Code let’s see how to use Node.js with visual studio code.

Step-3: Configure Visual Studio Code to use Node.js

3.1 Open Visual Studio Code

You can open Visual Studio Code using many GUI ways, but the fastest way is through the terminal or Windows Command Prompt.

3.2 Create a new file

You can create a file on the terminal and open it with Visual Studio Code. Alternatively, you can open an empty Visual Studio Code window, open the Explorer, and create a folder followed by a file.

Using Node.js with Visual Studio Code [Step-by-Step]

Besides, you can click the File tab on the navigation menu, followed by New File.

Using Node.js with Visual Studio Code [Step-by-Step]

Let’s create a file called server.js inside the test folder, then open it with Visual Studio Code. Head over to your Terminal, create a folder, and then open it with Visual Studio Code.

Using Node.js with Visual Studio Code [Step-by-Step]

Hover over the folder name. A menu pops on the right side of the folder name. The first link creates a file, while the second one creates a folder. The third link refreshes the screen, while the last one collapses all the (sidebar) opened files and folders. Let’s create the file using the first menu’s link.

Using Node.js with Visual Studio Code [Step-by-Step]

3.3 Write your first javascript code

Let’s write some JavaScript in the file.

Save the file using ctrl+s . And run it with Visual Studio Code’s Terminal. There are many ways to toggle the Terminal. You can use the main navigation links or shortcuts: ctrl+

Note: command for Mac is the equivalence of the ctrl key for Windows and Linux. So, it would be best to replace every ctrl instance with the command if the given visual studio code shortcut fails to work in Mac.

Now run the file with node.

You get the following output:

Similarly, you can use the Visual Studio Code Terminal to install packages.

Step-4: Install additional packages on VSC

Let’s install the following packages using the Terminal.

  • express: Create a web server
  • nodemon: Watch the server.

Before that, let’s notify Node.js that we want to manage npm packages by running npm init command.

Using Node.js with Visual Studio Code [Step-by-Step]

Let’s customize the package.json file to use nodemon , build the web server and start it.

Then make a request using your browser as the client on PORT 3000.

Using Node.js with Visual Studio Code [Step-by-Step]

You can end a process running on the terminal using the ctrl+c shortcut.

You must have realized that visual studio code is intelligent enough to detect we are writing JavaScript. It attempts to autocomplete statements for us.

Using Node.js with Visual Studio Code [Step-by-Step]

You probably wonder how I condensed the font size to accommodate more things or split the screen to accommodate the two files.

You can enlarge the font size by pressing the ctrl and + keys simultaneously or minimize it using the ctrl and — keys. You can split the screen by dragging one file to the top-right active corner of another.

Using Node.js with Visual Studio Code [Step-by-Step]

Step-5: Install extension packages on VSC

One of the main reasons programmers love Visual Studio Code is that you can build anything or use (almost) any programming language with it. It enables you to install extensions through its Extensions link on the sidebar.

All you do is click the Extensions link, search for a new or an installed extension then install or manage the extension.

Using Node.js with Visual Studio Code [Step-by-Step]

You can also manage extensions through the command palette, accessible through the View tab -> Command Palette

how to use Node.js with visual studio code

The command palette, also reachable via the ctrl+shift+p shortcut, enables you to run commands.

Themes like Eva, One Dark Pro, Cobalt 2, and Material Theme change the appearance of the UI of your code editor. For example, let’s install One Dark Pro, set its dark mode and see how the interface looks.

Using Node.js with Visual Studio Code [Step-by-Step]

Additionally, you can install the Prettier extension for automatic code format. Then open the server.js file to see the impact of themes and extensions.

Using Node.js with Visual Studio Code [Step-by-Step]

The file has a (better) new look.

Lastly, you can close the editor or open another project.

Conclusion

Knowing how to use Node.js with Visual Studio Code starts by installing Node.js and the editor on your machine.

You should then learn how to manage files by navigating Visual Studio Code’s interface. It would be helpful to know shortcuts and customize the editor for improved productivity.

Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *