How to debug "built" production NodeJS - node.js

I am using Visual Studio code to debug a node application in production environment
The Node process runs inside docker,
I port-forwarded and signaled USR1 to enable attaching debugger from VS code to that node process
My VS Code configuration is like this
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "attach",
"name": "Debug: service",
"sourceMaps": true,
"smartStep": true,
"remoteRoot": "/src/",
"localRoot": "/home/my-username/work/orders/src/",
"protocol": "inspector",
"port": 9229,
"restart": true,
"address": "0.0.0.0",
"skipFiles": [
"<node_internals>/**",
"<node_modules>/**"
]
}
]
}
From VS code, I can hook into the application and the application can break on exception
However there is no source-mapping which cause all my breakpoint in my source-code to be "unbound breakpoint"
The loaded script list in VS code show that
The VS code debugger is able to see the node_modules and the built version of my source code inside dist. One other notable point is that the source code that is used to build the /dist is also available directly in the production server, in the upper folder.
How can I debug the built production process, using my unbuilt source code in this case?
I added Chrome behaviour as separate question
NodeJs: Chrome inspector can map source but unable to debug on original source

I don't know whether it will be helpful to you or not. But I think you have to use node-inspector. It can be used from any browser supporting WebSocket. It is really good.
Cool stuff
Node Inspector uses WebSockets, so no polling for breaks.
Remote debugging and debugging remote machine.
Live edit of running code, optionally persisting changes back to the file-system.
Set breakpoints in files that are not loaded into V8 yet - useful for debugging module loading/initialization.
Embeddable in other applications - see Embedding HOWTO for more details.

Node already ships with an integrated debugger. However, it doesn’t have a GUI, so you need to use the command line version.
You can launch this debugger using node debug.
$node debug test.js
< Debugger listening on port 5858
debug> . ok
break in test.js:1
> 1 var a= 5;
2 a = a*a
3 a += 2;
debug>
It shows you where it’s paused and then lets you control execution with commands like next and cont.
debug> next
break in test.js:2
1 var a= 5;
> 2 a = a*a
3 a += 2;
4
The repl and watch commands allow you to see the values of local variables.

Related

VSCode NodeJs: Debugger not stopping at breakpoint (WSL2/Ubuntu18)

Using WSL2/Ubuntu18 I've not been able to make the VSCode NodeJs Debugger to stop on the breakpoints of any NodeJs app. When I start the debugger, it runs (I can see the output on the integrated terminal) but breakpoints are simply ignored.
The simple.js file, with a breakpoint on line 3:
The launch.json is set to:
{
"version": "0.2.0",
"configurations": [
{
"name": "NodeJs: Launch Program",
"program": "${file}",
"request": "launch",
"skipFiles": [
"<node_internals>/**"
],
"type": "pwa-node",
"console": "integratedTerminal"
}
]
}
When I press F5 or click on the "Start Debugging" button on VS Code, the app runs and following appears on the integrated Terminal:
/usr/bin/env 'NODE_OPTIONS=--require /home/myuser/.vscode-server/bin/ea3859d4ba2f3e577a159bc91e3074c5d85c0523/extensions/ms-vscode.js-debug/src/bootloader.bundle.js --inspect-publish-uid=http' 'VSCODE_INSPECTOR_OPTIONS={"inspectorIpc":"/tmp/node-cdp.19338-1.sock","deferredMode":false,"waitForDebugger":"","execPath":"/home/myuser/.nvm/versions/node/v14.15.1/bin/node","onlyEntrypoint":false,"autoAttachMode":"always","fileCallback":"/tmp/node-debug-callback-ff32d873905abafa"}' /home/myuser/.nvm/versions/node/v14.15.1/bin/node ./simple.js
Debugger attached.
0
1
2
3
4
Waiting for the debugger to disconnect...
I've already upgraded from Node10 to Node14, but the problem persists.
On another computer using WSL1, and using the same launch.json the debugger stops at the given breakpoints. Do I need to set something additionally on WSL2? For the record, this is what appears on the integrated terminal on the WSL1 computer before it stops at line 3:
/usr/bin/env 'NODE_OPTIONS=--require /home/myuser/.vscode-server/bin/ea3859d4ba2f3e577a159bc91e3074c5d85c0523/extensions/ms-vscode.js-debug/src/bootloader.bundle.js --inspect-publish-uid=http' 'VSCODE_INSPECTOR_OPTIONS={"inspectorIpc":"/tmp/node-cdp.787-3.sock","deferredMode":false,"waitForDebugger":"","execPath":"/home/myuser/.nvm/versions/node/v14.15.1/bin/node","onlyEntrypoint":false,"autoAttachMode":"always","fileCallback":"/tmp/node-debug-callback-b901b6d6e3e9799b"}' /home/myuser/.nvm/versions/node/v14.15.1/bin/node ./simple.js
Debugger attached.
<Breakpoint hit and stop...>
Additional info, debugging Python3 files work correctly on both machines.
Both computers have the same VS Code Version installed.
Update:
You can follow the issue on GitHub: https://github.com/microsoft/vscode/issues/113283
The problem is that the NodeJs App is being run from a symlinked address - so the debugger can not handle it.
Answer from one of the developers of VSCode/NodeJS on github:
It looks like you have your script symlinked into /bin/nhosko/simple.js, but its actual location is /mnt/c/Users//bin-nhosko/simple.js. In this case you need to specify some flags so that Node will report the linked location that vscode sees and told the debugger about: https://code.visualstudio.com/docs/nodejs/nodejs-debugging#_can-i-debug-if-im-using-symlinks. I want to make the debugger smart enough to fix this automatically in microsoft/vscode-js-debug#776.
https://github.com/microsoft/vscode/issues/113283#issuecomment-750371948

VS Code remote debug to NodeJs in cluster

I am trying to remotely debug NodeJs application, which uses clusters. When I run my app locally, and I am attaching to it, VS Code see child processes and breakpoints works:
VS Code Config:
{
"name": "Attach",
"type": "node",
"request": "attach",
"port": 50131,
"internalConsoleOptions": "neverOpen",
"skipFiles": ["<node_internals>/**"],
"autoAttachChildProcesses": true
},
VS Code result:
However, in remote host, process starts same way, same port, I am able to attach debugger to it, but VS Code Can't see child processes and source maps (to connect local files breakpoints to remote, in debug config I have correct host address):
So the difference between local env and remote is Windows vs Unix, and in remote app is run via Forever (module, however, even Forever, without clusters remote debugging works correct).
Where can be an issue?
EDIT: I can't use SSH debug in my organization.
Give vscode extension Remote SSH a try. It let you run remote code locally.
https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-ssh

Cannot use 'autoAttachChildProcesses' to debug forked processes

I cannot debug forked node processes.
The forked process launches and behaves as expected; however, the debugger does not pause on breakpoints of the forked code.
Hovering over the breakpoint shows Unverified breakpoint tooltip. In addition, the Debug activity bar shows Breakpoint set but not yet bound:
I have 2 javascript files. The first forks the other:
index.js
const child_process = require("child_process");
console.log(process.argv[0]);
process.execArgv.push('--debug=' + (40895));
child_process.fork('./m1.js');
m1.js
console.log(`from fork: ${process.argv[0]}`);
launch.json
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "run.vscode",
"program": "${workspaceFolder}/index.js",
"autoAttachChildProcesses": true
}
]
}
I'm using node v10.16.0 and the issue is reproducible in vscode 1.36.0-insider and in 1.34.0; in Windows 10 or in WSL using the Remote - WSL extension.
Is the autoAttachChildProcesses property even supported for child_process.fork() or only for cluster.fork()?
I made it work by passing the --inspect-brk flag through the execArgv option of the fork() method:
child_process.fork('./m1.js', [], {execArgv:['--inspect-brk=40895']});
See more details in a corresponding issue I opened on GitHub.

Debug Mocha tests being executed via NPM in terminal of VSCode

Does anyone know how to configure VSCode to debug Mocha tests when executing via a test script? Setup is:
"test" config in package.json of project specifying the mocha command to execute( mocha -R mochawesome -s 3000 -t 30000 ./index.js )
'npm test' command used in internal terminal of VSCode with '-g' param to allow for execution of specific descriptions within CoffeeScript test files
I want to be able to debug the execution of these individual tests(i.e. run 'npm test -- -g "test description"' in VSCode and break in VSCode's Debug view when it reaches a bp). Is this possible? Would an 'attach' config be needed instead of 'launch'?
I've tried the standard debug configs provided in VSCode , and tried to modify them based on info found in various places, but no success so far. Any help would be great, not too familiar with the IDE, or any of these processes Thanks!
Late answer but it may help people falling on this question.
Adding inspect-brk will hold the process until you connect your debugger, vscode in this case. After that tests will run and stop on your debug points. Usually the listening port for debugging is 9229, but you'll see the correct port on the sysout.
mocha --inspect-brk test.js
Credits to Run node inspector with mocha
You can attach vs code debugger to a process launched by script
For that you need to:
1) Add mocha's --inspect option to your script
2) Configure your launch.json this way
"configurations": [
{
"type": "node",
"request": "attach",
"name": "Mocha: tests",
"processId": "${command:PickProcess}",
"restart": true,
"protocol": "inspector",
},
]
3) After running your script hit F5 and pick mocha's process from vs code popped up processes list (you need to be quick here :) )
4) Second time you run the script and hit F5 vs code will automatically pick the right process for you

Visual Studio Code node.js debugging: "Connection failed" error

I am following exactly the official guide: https://code.visualstudio.com/Docs/nodejs
At the end of the guide:
"...and press F5 to start debugging"
I get the following error:
Error Connection failed
I use Debian Jessie.
I'm running VSCode v0.3.0 on GNU/Linux Ubuntu 12.04 LTS x64.
I can use the builtin VSCode debugger and use VSCode to attach to a node process running in debug mode.
You mentioned you are running debian/jessie GNU/Linux and Express and Node are listed in your tags so the following may be of some help.
Make sure you don't have any running node processes that would conflict with the connection by launching a System Monitor type application ( or app or command line tool of your choice ) and kill any node or nodejs processes that may not have been exited properly.
Double check your installation location of Mono and that it's version is v3.12 or higher (v4.0.1 or higher if developing for vNext ASP.net 5).
You can install Mono using any method you like as long as it's version is v3.12 or higher. I elected to download, compile and install Mono under /opt for my distribution from the mono-project.
15:15:34 ツ gjsmith3rd#DV7:~ >which mono
/opt/mono/mono-4.0.1/bin/mono
15:15:38 ツ gjsmith3rd#DV7:~ >mono --version
Mono JIT compiler version 4.0.1 (tarball Wed Jun 3 09:11:07 CDT 2015)
Copyright (C) 2002-2014 Novell, Inc, Xamarin Inc and Contributors. www.mono-project.com
TLS: __thread
SIGSEGV: altstack
Notifications: epoll
Architecture: amd64
Disabled: none
Misc: softdebug
LLVM: supported, not enabled.
GC: sgen
You'll want to take note of your Mono installation location for your environment configuration. In my case the location is /opt/mono/mono-4.0.1/*. You'll need to change the location to reflect your actual environment. Once you've determined the correct version and installation location ensure that the installation has correctly configured environment variables in your .bashrc, .bash_profile or relevant shell environment for your distribution.
```
export PATH=/opt/mono/mono-4.0.1/bin:$PATH
export MONO_LOG_LEVEL=debug
export MONO_LOG_MASK=asm
export LD_LIBRARY_PATH=/opt/mono/mono-4.0.1/lib:$LD_LIBRARY_PATH
export PKG_CONFIG_PATH=/opt/mono/mono-4.0.1/pkgconfig
export MONO_PATH=/opt/mono/mono-4.0.1/lib
```
Again, the paths need to reflect the locations in your environment. If you make any changes to your environment source your shell or logout and login.
$source .bashrc
Launch VSCode or close and relaunch VSCode.
In your VSCode debug config file (click the gear symbol in debug for Launch Configuration) launch.json make sure your app being debugged is node: "type": "node".
```
{
"version": "0.1.0",
// List of configurations. Add new configurations or edit existing ones.
// ONLY "node" and "mono" are supported, change "type" to switch.
"configurations": [
{
// Name of configuration; appears in the launch configuration drop down menu.
"name": "Launch server.js",
// Type of configuration. Possible values: "node", "mono".
"type": "node",
// Workspace relative or absolute path to the program.
"program": "server.js",
// Automatically stop program after launch.
"stopOnEntry": true,
// Command line arguments passed to the program.
"args": [],
// Workspace relative or absolute path to the working directory of the program being debugged. Default is the current workspace.
"cwd": ".",
// Workspace relative or absolute path to the runtime executable to be used. Default is the runtime executable on the PATH.
"runtimeExecutable": null,
// Environment variables passed to the program.
"env": { }
},
{
"name": "Attach",
"type": "node",
// TCP/IP address. Default is "localhost".
"address": "10.0.0.57",
// Port to attach to.
"port": 5858
}
]
}
```
Save any changes.
If you want to attach to a running node process then start the node app from the command line in the directory of your app.
$node debug appname.js
You can now use the node command line to continue the debugging process.
```
17:37:51 ツ gjsmith3rd#DV7:(master)~/Workspaces/Development/devsandbox >node debug server.js
< Debugger listening on port 5858
debug> . ok
break in server.js:5
3
4 // OpenShift sample Node application
> 5 var express = require('express');
6 var fs = require('fs');
7 // var bootstrap = require("bootstrap");
debug> next
break in server.js:6
4 // OpenShift sample Node application
5 var express = require('express');
> 6 var fs = require('fs');
7 // var bootstrap = require("bootstrap");
8
debug>
```
or launch VSCode and attach the debugger to the running node debug process. Make sure your VSCode Launch Configuration has an attach entry that is properly configured and run it from within VSCode by selecting the debugger pull down menu. You'll want to configure the IP and port to you requirements.
```
{
"name": "Attach",
"type": "node",
// TCP/IP address. Default is "localhost".
"address": "localhost",
// Port to attach to.
"port": 5858
}
```
Finally, you should be able to launch the debugger from VSCode without using the command line by using the VSCode debug pull down menu and selecting your configured JS or Node app and pressing the debugger play button.
Click the green play button in you VSCode debugger and it should open a terminal listing the debugging port while attaching to the process.
Debugger listening on port 38569
If all is well you should now be able to start the node app with the debugger controls within VSCode using the second play (continue) button (continue, step over, step into, step out and stop).

Resources