debug nestJS application with nodemon in VS Code - node.js

Is there a way to debug a nestJS project with nodemon.
i tried this code in launch.json
{
"type": "node",
"request": "launch",
"name": "NestJs Watch",
"runtimeExecutable": "npm",
"runtimeArgs": ["run-script", "start:dev"],
"cwd": "${workspaceFolder}",
"port": 3000
}
but i got this error
and my nodemon.json file
{
"watch": ["src"],
"ext": "ts",
"ignore": ["src/**/*.spec.ts"],
"exec": "ts-node -r --inspect=3000 tsconfig-paths/register src/main.ts"
}

If we want to work in the debug mode, with a better chance to see what is happening in the code, we need to use "nodemon" with dedicated a "nodemon.json" configuration file to run our development "nestjs" server with the ts-node module hooking up the typescript compiler.
The steps that worked for me are:
Install nodemon and ts-node:
npm i --save-dev nodemon ts-node
Next, add a nodemon.json file with debug and ts-node support in the root of your project:
file: (project root) nodemon.json
and insert this config. JSON text:
{
"watch": ["src"],
"ext": "ts",
"ignore": ["src/**/*.spec.ts"],
"exec": "node --inspect-brk -r ts-node/register src/main.ts"
}
Next adjust file: package.json - section: "start:debug"
file: (project root) package.json
The original value typically is:
...
> "start:debug": "nest start --debug --watch",
...
Change it to:
...
> "start:debug": "nodemon --config nodemon.json"
...
Now, in VSC (Visual Studio Code) make sure that you can see on the very bottom status bar:
"Auto Attach: On"
if not, on your keyboar press the keys:
Ctrl + Shift + p
to open the Command Palette, and paste in this command:
Debug: Toggle auto attach
and press Enter.
Now you should see the:
"Auto Attach: On"
Now debugging with break points should work.
Start with placing a break point in the beginning of your program code
(to make sure the flow does not end before your breakpoint ...)
file: (project root) 'main.ts'
> function: bootstrap() {
console.log('test'); // -- place break point here
// ... other code ...
}
In VSC (Visula Studio Code) select menu item:
Start debugging (or F5)
and select Node.js as the Environment option in the popup menu.
The breakpoint should be caught now in the bootstrap() function.

I run this command:
npm run start:dev

Try this nodemon config:
{
"watch": ["src"],
"ext": "ts",
"ignore": ["src/**/*.spec.ts"],
"exec": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register src/main.ts"
}
and then you can run: nodemon --config nodemon.json

Related

Loopback 4 Debugger nodemon Solution

How to debug loopback 4 / node application with nodemon in visual studio code?
Looking for a solution that rebuilds the app when the loopback typescript code is changed. With option for debugging.
Regards,
Kelvijn
I finally found a solution to debug Loopback 4/node.js. If anyone has suggestions please do, this is the first solution that really does what I want.
Start Debugger by running:
npm run debug
With nodemon run the below command
nodemon --exec run debug
Add breakpoints by clicking on the left side of the line numbers in visual studio code.
Then in Visual Studio Code start application on debug mode by
Visual Studio Code (top-bar) -> Debug -> Start Debugging
package.json
"debug": "npm run build && node --nolazy --inspect-brk=9229 .",
"build": "lb-tsc es2017 --outDir dist"
launch.json
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "attach",
"timeout": 1000000,
"name": "Attach",
"port": 9229,
"restart": true
}
]
}
tsconfig.json
Note: This file is by default extended by loopback, so you don't have to modify this.
{
"compilerOptions": {
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "ES5",
"lib": ["es2015"],
"allowJs": true,
"skipLibCheck": true
},
"include": ["src"],
"exclude": ["node_modules", "platforms"]
}
Application structure
This is an alternative solution for nodemon.
tsc-watch is a similar tool that can be used with loopback 4. Basically, it works similar to the nodemon. To add tsc-watch as dev package,
run npm install tsc-watch --save-dev in your project location
add following lines to the package.json > scripts
"start": "node -r source-map-support/register .",
"dev": "tsc-watch -b --onSuccess \"npm start\""
now run npm run dev
For more details visit tsc-watch on npm or github
Create your own nodemon.json in root project source and put this in file
{
"ignore": [
"**/*.test.ts",
"**/*.spec.ts",
".git",
"node_modules"
],
"watch": [
"src"
],
"exec": "npm start",
"ext": "ts"
}
and run nodemon that's. Just make sure you installed nodemon in global scope.
Thanks for all the answers here I have manage to have something that works for my setup. I use yarn with loopback 4. Thanks to #dat-ho for the starting point.
First install nodemon in global scope
then add the nodemon config to package.json. I added this at the bottom of the file after devDependencies.
"nodemonConfig": {
"verbose": true,
"watch": [
"src/"
],
"ignore": [
"dist/*"
],
"ext": "ts",
"exec": "yarn run clean && yarn start"
}
The changes from previous answer was that nodemon detects the npm start script and it re runs npm start fine, but it does not rebuild and the changes were not shown in the running code. so I added the line "exec": "yarn run clean && yarn start" to clean and rerun the npm start command.
You can then add the following start:dev command to the package.json scripts section:
"start": "node -r source-map-support/register .",
"start:dev": "nodemon '--inspect'",
From there just run yarn start:dev and will rebuild when any typescript file changes. Hope this works for you guys. It took me a substantial amount of research to having this working. Hopefully the loopback guys can have something similar in future.

Can't get VSCode debbuging to work with my NodeJs app

I'm having trying to debug my app on Visual Studio Code. I have the following config on my package.json:
"scripts": {
"build": "rimraf dist/ && babel ./ --out-dir dist/ --ignore ./node_modules,./.babelrc,./package.json,./npm-debug.log --copy-files",
"start": "npm run build && node --inspect=12345 dist/app.js"
}
Im using ES6 on my Node app, that's why it is kinda messy my build config.
When I run npm start everything works fine, I can use my app.
Now to try to debug it, I have set the following launch configurations:
"configurations": [
{
"type": "node",
"name": "Attach to Remote",
"request": "attach",
"port": 12345
},
{
"type": "node",
"request": "launch",
"name": "Launch Program",
"program": "${workspaceFolder}\\dist\\app.js"
}
]
Both of them ""work"": VS Code switch to "debug mode" but I can't hit any breakpoints. They all get grayed out:
I have tried to fix using this answer, but couldn't get it to work...
Any help?
Thanks in advance!
I am using VS Code v 1.28.2 and I'm able to debug both ways.
1) With the built in debuger ( Menu -> Debug -> Start Debuging)
2) starting the application with node inspect index.js. In that case you have to declare breakpoints in your code with the debugger; keyword. Then, when in debug-mode and stoped in a breakpoint, you continue execution typing cont in the command line.
hope it helps
I found out I was just missing the --source-maps from my babel-cli command... -.-
After adding it, VSCode is able to find the breakpoints.
So basically the solution was:
Add --source-maps to my build command:
"scripts": {
"build": "rimraf dist/ && babel ./ --out-dir dist/ --ignore ./node_modules,./.babelrc,./package.json,./npm-debug.log --copy-files --source-maps",
"start": "npm run build && node --inspect=12345 dist/app.js"
}
And I configured a launch as follows:
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Launch Program",
"program": "${workspaceFolder}\\dist\\app.js",
"preLaunchTask": "npm: build"
}
]
Hope it helps someone!

Use flag `--experimental-worker` with babel-node

babel-node --experimental-worker app.js
Using this command for starting my project in development mode. Output is:
error: unknown option--experimental-worker'
config .babelrc:
{ "presets": [ ["env", { "targets": { "node": "current" } }], "stage-0", "flow" ], "plugins": [ "transform-decorators-legacy", "transform-flow-strip-types" ] }
This flag is needed to use worker threads. Using babel 6.26
I just ran into this today and replied to the issue on GitHub here. I've pasted my fix below:
I was using Nodemon, and it turns out that there's an option to
include environment variables as NODE_OPTIONS in the nodemon.json
file. This did the trick for me:
{
"watch": ["server"],
"ext": "js",
"env": {
"NODE_OPTIONS": "--experimental-worker"
},
"exec": "babel-node server/server.js"
}
How to integrate Nodemon + worker_threads into a normal NodeJS app:
Set up Nodemon
Add a nodemon.json file to the root folder (example here)
Add this to nodemon.json:
"env": {
"NODE_OPTIONS": "--experimental-worker"
}
If you're setting up Nodemon for the first time, I found
this tutorial very helpful.
The idea is to split your command into two phases:
Phase 1:
babel app.js --out-file app-compiled.js
And phase 2:
node --experimental-worker app-compiled.js
In npm scripts you can then combine the two:
"scripts": {
"pre-build": "babel ./app.js --out-file ./app-compiled.js",
"serve": "yarn pre-build && node --experimental-worker ./app-compiled.js"
}
It not actually for me already. I am refused to use nodemon and run my code with command
node --experimental-worker -r babel-register $NODE_DEBUG_OPTION app.js
It`s help me use exeprimental workers with babel, but with nodemon - not

Unable to debug the Nodejs application in Visual studio code

I have launch configuration for my Nodejs with ExpressJs application, the debugger mode starts and then immediately stops.. It doesn't keep on listening.. any help is much appreciated.
{
"name": "Launch via NPM",
"type": "node",
"request": "launch",
"cwd": "${workspaceFolder}/index.js",
"runtimeExecutable": "npm",
"runtimeArgs": [
"run-script", "debug"
],
"port": 9229
}
Below is my server configuration
app.listen(PORT, HOST, () => {
process.stdout.write(Server is listening on ${PORT} (${NODE_ENV})\n)
log.info(Server is listening on ${PORT} (${NODE_ENV})\n)
})
Start commands in package.json
"devStart": "nodemon --exec babel-node index.js",
"start": "per-env",
"start:development": "nodemon --exec babel-node index.js",
The issue is resolved by below steps..
1.) Followed the steps as suggested by Mickers in the above comments
2.) (for the async module issue ) rm -rf node_modules
followed by -- npm install
The debugger is successfully attached

Running NodeJS project in Visual Studio Code with yarn

I have a NodeJS project which I can start from command line with yarn start command. My package.json looks similar to this:
{
"name": "projectname",
"version": "0.0.1",
"description": "",
"author": "My Name",
"license": "",
"scripts": {
"start": "yarn dev",
"dev": "yarn stop && pm2 start pm2-dev.yaml && webpack-dev-server --progress",
"prod": "yarn stop && yarn build && pm2 start pm2-prod.yaml",
"build": "rimraf dist lib && babel src -d lib --ignore test.js && cross-env NODE_ENV=production webpack -p --progress",
"stop": "rimraf logs/* && pm2 delete all || true"
},
"dependencies": {
"body-parser": "~1.16.0",
"ejs": "2.5.5",
"express": "^4.14.1",
"pg": "^6.1.2",
"react": "^15.4.2",
"redux": "^3.6.0",
},
"devDependencies": {
"babel-cli": "^6.22.2",
"cross-env": "^3.1.4",
"eslint": "^3.13.0",
"pm2": "^2.3.0",
"redux-mock-store": "^1.2.2",
"rimraf": "^2.5.4",
"webpack": "^2.2.1",
"webpack-dev-server": "^2.2.1"
}
}
I am trying to start this project in debugging mode with Visual Studio Code but with almost no luck. I have defined my launch configuration in VS Code launch.json file like this:
{
// Use IntelliSense to learn about possible Node.js debug attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "yarn",
"runtimeExecutable": "yarn",
"runtimeArgs": [
"start"
],
"port": 5858,
"cwd": "${workspaceRoot}",
"timeout": 10000
}
]
}
The problem with this configuration is that it usually times-out because webpack-dev-server build is longer than 10 seconds. I can increase the timeout in my configuration, but I have noticed that VS Code results with a message Cannot connect to runtime process (timeout after 30000 ms). eventually, so I assume that this is not a good solution. Also, my breakpoints are ignored with this kind of config which tells me that I am definitely doing something wrong here.
This is the first time I am trying out Visual Studio Code and I usually don't use NodeJS, but I got this project with all these scripts in package.json already defined so I'm trying to adopt to it and therefore all the confusion about how to run it properly.
Can Visual Studio Code run a project like this with full debugging functionality at all, and if so, how should I configure my launch script?
I ended up having the following configuration in launch.json:
{
"type": "node",
"request": "launch",
"name": "Launch via Yarn",
"runtimeExecutable": "yarn",
"cwd": "${workspaceFolder}",
"runtimeArgs": ["start:debug"],
"port": 5858
}
And the following entry in the scripts property inside package.json:
"start:debug": "node --inspect-brk=5858 ./server/index.js",
You could include a timeout key (which defaults to 10000) and increase its value if have any prestart:debug script in your package.json which could lead to delay the launch of the actual node app.
I can't specifically answer the webpack parts of the question. However, your script above won't work because you haven't enabled debugging. Exposing debugging allows a debugger to attach to this process, and it also blocks program execution until a debugger attaches. You'll need to make another script in your package.json that allows for debugging. Then, you can use your debugging-specific script to debug and your non-debugging script to run normally. For example:
"scripts": {
"start": "yarn dev",
"dev": "node entry.js",
"dev-debug": "node --inspect-brk=5858 entry.js",
Then, in your launch.json replace "start" with "dev-debug". The debugging port is already set to 5858 in both launch.json and package.json, so this should work. The key is running node with the --inspect-brk command, forcing the execution of the node app to stop until a debugger attaches to it.
Additionally to the above - to get mine working I had to add the following to my package.json (the exec was still required) -
"start:debug": "nodemon --inspect-brk=5858 --exec \"babel-node\" src/index.js"
Haven't used the debugged in VS Code however I'm using nodemon to debug with Chrome with a shell script.
bin_dir="$__dirname/../node_modules/.bin"
src_dir="$__dirname/../src"
"$bin_dir/nodemon" --ext js,yaml \
--watch "$src_dir/package.json" \
--watch "$src_dir" \
"$src_dir/index.js" \
--exec "yarn && babel-node --inspect=0.0.0.0:9229"
Open chrome://inspect/#devices and start up your debugger
Thanks for the information shared in this thread, What exactly is the 'react-scripts start' command?, by #johndpope.
Here is the setup I used in vscode's launch.json file in configurations section for launching a react process.
{
"name": "Launch: Frontend Server",
"program": "${workspaceFolder}/node_modules/react-scripts/bin/react-scripts.js",
"args": ["start"],
"request": "launch",
"type": "node",
"console": "integratedTerminal",
"localRoot": "${workspaceFolder}",
}
So, response to the original post, you may try to see what is the script used in rimraf library.

Resources