Home > Software design >  Beginner having trouble running Javascript on Visual Studio Code
Beginner having trouble running Javascript on Visual Studio Code

Time:11-08

New coder here. As the title suggests, I spent the past two hours trying to run a simple Javascript on VSC with no avail. Could someone help me set my sandbox up? Here is a screenshot.

enter image description here

Much appreciated!

kt

  1. Downloaded VSC
  2. Downloaded nodejs
  3. Entered "node scriptname.js" in terminal
  4. Error message above

CodePudding user response:

Your specific error is caused by you running node from the console and providing the wrong path to test.js.

You are in the Desktop directory and just specifying a file name, so Node is looking for test.js in the Desktop directory.

You have saved test.js in a directory called Coding Practice.

You need to either:

  • cd to the correct directory or
  • Provide the path to the directory as part of the second argument

Typically, when using VS Code, you would pick the Open Folder option from the File menu to work within your project's root directory (i.e. Coding Practice) which will provide you with a file list and do things like open the terminal in that directory by default.


Once you solve that problem you will run into your second problem.

The contents of test.js isn't JavaScript!

It's an HTML document with JavaScript embedded in it.

You need to:

  • Give it a .html file extension and
  • Open it using a web browser and not with Node.js (the traditional way to do that from within VS Code is with the live server extension but you'll really want to have VS code open in the right directory (as above) for that.)

You can't even remove the HTML from the file and run it with Node.js because alert (the function you call) is a Web API and not core JavaScript nor a Node.js API.

CodePudding user response:

I suppose you have file TEST1.js under folder Coding Practice. Since you are executing from Desktop it is taking path /Users/kt/Desktop/test1.js

Change directory to Coding Practice inside Desktop and try running your file.

Actual path of the file should be /Users/kt/Desktop/Coding Practice/test1.js

cd Coding\ Practice

P.S. Also instead of opening Desktop folder in VSC, open Coding Practice and do what you have did earlier.

  • Related