jdb79
jdb79

Reputation: 921

Debugging current file in VS Code

I am writing javascript and am currently doing simple exercises/programs. At times, I wish to run my file for testing purposes. I am aware I could create an HTML file and do this within the console. In Sublime, there exists a way to "build" the current file and immediately see the results (say, whatever is sent to console.log).

With VS Code, it seems that for every file I want to "build"/debug in this manner, I must manually change the launch.json file to reflect the name of the current program.

I have been researching a way around this, and I learned that there are variables like ${file} , but when I use that in the launch.json "program" attribute, for example:

"program": "${workspaceRoot}/${file}"

with or without the workspaceRoot part, I get the following error:

Attribute "program" does not exist" (file name here). 

Am I missing a simple way to accomplish this, or must I keep editing launch.json every time I want to run the file?

Thanks in advance!

Upvotes: 92

Views: 55057

Answers (4)

KyleMit
KyleMit

Reputation: 29909

There are many different ways you may need to access a file that are provided by Predefined variables:

Supposing that you have the following requirements:

  • A file located at /home/your-username/your-project/folder/file.ext opened in your editor;
  • The directory /home/your-username/your-project opened as your root workspace.

So you will have the following values for each variable:

  • ${userHome} - /home/your-username
  • ${workspaceFolder} - /home/your-username/your-project
  • ${workspaceFolderBasename} - your-project
  • ${file} - /home/your-username/your-project/folder/file.ext
  • ${fileWorkspaceFolder} - /home/your-username/your-project
  • ${relativeFile} - folder/file.ext
  • ${relativeFileDirname} - folder
  • ${fileBasename} - file.ext
  • ${fileBasenameNoExtension} - file
  • ${fileDirname} - /home/your-username/your-project/folder
  • ${fileExtname} - .ext
  • ${lineNumber} - line number of the cursor
  • ${selectedText} - text selected in your code editor
  • ${execPath} - location of Code.exe
  • ${pathSeparator} - / on macOS or linux, \ on Windows

Upvotes: 13

Ricardo Mayerhofer
Ricardo Mayerhofer

Reputation: 2309

For reference this is the full launch.json

{
  "launch": {
    "version": "0.2.0",
    "configurations": [
      {
        "name": "Node.js - Debug Current File",
        "type": "node",
        "request": "launch",
        "program": "${file}"
      }
    ]
  }
}

Upvotes: 77

samlandfried
samlandfried

Reputation: 821

For a single file, you can skip the launch.json file entirely. Just click the green arrow in the debugger panel and choose Node as your environment.

From here.

Upvotes: 1

jfriedman
jfriedman

Reputation: 2181

Change to:

"program": "${file}"

Upvotes: 202

Related Questions