How to Debug ServerSide JavaScript(NodeJS) and TypeScript with VS Code

Summary

Basic

Spec

Instruction

mocha (unit test framework)

npm install --save-dev mocha assert

for Java Script

add settings for Mocha

{
  "mochaExplorer.files": ["src/test/**/*.js"]
}

using Test Explrer and Codelens

for Type Script

using ts-node

npm install ts-node

add settings for Mocha

{
  "mochaExplorer.files": ["src/test/**/*.js", "src/test/**/*.ts"],
  "mochaExplorer.require": "ts-node/register"
}

using Test Explrer and Codelens

executable file debug

for Java Script

Use following launch.json

{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "launch",
      "name": "Launch js",
      "program": "${workspaceFolder}/src/bin/bubble_sort_js.js",
      "args": ["4", "3", "2", "1"]
    }
  ]
}

for Type Script (using compiled files)

There are compiled Type Script in out/. Use following launch.json.

{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "launch",
      "name": "Launch ts (using out/)",
      "program": "${workspaceFolder}/out/bin/bubble_sort_ts.js",
      "args": ["4", "3", "2", "1"],
      "sourceMaps": true,
      "preLaunchTask": "tsc"
    }
  ]
}

for Type Script (using ts-node)

ts-node allows executing Type Script directly.

{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "launch",
      "name": "Launch ts (using ts-node)",
      "program": "${workspaceFolder}/src/bin/bubble_sort_ts.ts",
      "runtimeArgs": ["--nolazy", "-r", "ts-node/register/transpile-only"],
      "args": ["4", "3", "2", "1"],
      "sourceMaps": true
    }
  ]
}

attach running process

launch.json

{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "attach",
      "name": "Attach by Process ID",
      "processId": "${command:PickProcess}"
    }
  ]
}

how-to

  1. run program with inspect options
    • when you like to break a first line, add --inspect-brk option
node --inspect --inspect-brk ./bin/bubble_sort.js
  1. start debug
  2. select process id
    • attach_running_process.png

remote process

launch.json

{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "attach",
      "name": "Attach to Remote",
      "address": "localhost",
      "port": 9229,
      "localRoot": "${workspaceRoot}",
      "remoteRoot": "${workspaceRoot}"
    }
  ]
}

how-to

  1. run program with inspect options
    • when you like to break a first line, add --inspect-brk option
node --inspect=0.0.0.0:9229 --inspect-brk ./bin/bubble_sort.js
  1. start debug