Can I profile NodeJS Applications using Visual Studio Code? - javascript

I can successfully connect the VS Code debugger to my remote NodeJS target using the Chrome protocol. I believe that same protocol supports profiling and performance measurements as it is easy to do from Chrome Dev Tools, but I am not sure it is something I can do from VS Code directly.
Is there any support for this feature ? How can I use it ?

Visual Studio Code 1.45 (April 2020) should help, as it integrates Javascript debugging capabilities, including profiling:
New JavaScript debugger
This month we've continued making progress on our new JavaScript debugger.
It's installed by default on Insiders, and can be installed from the Marketplace in VS Code Stable.
You can start using it with your existing launch configurations by enabling the debug.javascript.usePreview setting.
Here are some new features added this month:
Profiling Support
You can capture CPU profiles from your Node.js or browser applications by clicking the new "Profile" button in the Call Stack view, or using the Debug: Take Performance Profile command.
Once you do, you can choose how long the profile will run: until you stop it, for a length of time, or until you hit another breakpoint.
After the profile ends, it's saved in your workspace folder and visualized in VS Code.
When you open the profile, code lenses are added to your files containing performance information at a function level and for certain 'hot' lines.
Unlike profiles captured in many other tools, the recorded profile is sourcemap-aware.
cheesus mentions in the comments having an problem with the line numbers in the profiler output.
Hence microsoft/vscode-js-debug issue 559:
Turns out this is because that location is inside a function that only exists in the compiled code.
We actually do try to source-map it back into the original file, but there's no mapping at that location to use.
If you change your target to es6 or newer -- which you can do nowadays unless you're targeting Internet Explorer or Node versions <= 4 -- TS does not need to generate this stuff and line numbers work.
Your code will also run faster. Here's the latest mappings
This debugger only supports Node 8 and above.
Due to the fact that this bug is only present when targeting old JavaScript versions when using in-place transpilation on code compiled for a version of Node older than what the debugger itself supports, and the complexity involved in fixing this, I will close this issue as out-of-scope.

There is no plugin/support that I am aware of for initiating the profiling, or heap dumps, etc that are available in Chrome's Dev Tools. But, the VS Code debugger can work alongside the dev tools debugger.
Start from VS Code, and start debugging as you would. Then open dev tools from any tab in the Chrome/Chromium browser, and look for the green icon indicating a node.js debugging process is running (manually done via node --inspect):
.
Click this green icon and you'll have many of the browser dev tools features for debugging the node.js process, specifically the memory and profiler tabs.

Yes, There are many ways.
go to package.json and set:
{
\\ other information
"scripts": {
"debug": "node --inspect-brk"
}
}
after, run use command: npm run debug yourFile.js
or
you can execute in oneline node --inspect-brk yourFile.js
after this:
open chrome and go chrome://inspect
wait for a few seconds, to appears a remote target and click inspect
you can use debbuger; in your code to make a breakpoint.
To learn more go to the documentation.
In alternative you can use a plugin for VS code 'Debugger for Chrome' and follow the guide.

I suppose it worth mentioning here that you can profile nodejs app using plain console.profile and console.profileEnd. It will generate .cpuprofile file in the project root folder which you can open then with VSCode. E.g. I used it to profile Mocha tests.

Related

Chrome Debugger for JS file only

So. Dumb question.
I am using developer tools on chrome as essentially my IDE in the source tab. I have a JS file writing a program with no associated html/css files. Is there anyway for me to utilize the debugger for my JS file? Specifically I want to step into a function
In developer mode, select Sources tab, then navigate to your JS files in the left side. In the right panel, you can add a breakpoint to any line by pressing the line number which has a real js statement. Then you can run your application again to debug your js scripts.
The picture below is an example(Line 33 of assert.js is selected).
There are a number of different ways to debug/test your JS code, Chrome is only one of them.
QUOKKA
Quokka.js is a developer productivity tool for rapid JavaScript / TypeScript prototyping. Runtime values are updated and displayed in your IDE next to your code, as you type.
Runkit notebook
RunKit notebooks completely remove the friction of trying new ideas. With one click you’ll have a sandboxed JavaScript environment where you can instantly switch node versions, use every npm module without having to wait to install it, and even visualize your results. No more configuration, just straight to coding.
Hopa
Hopa is a zero config JavaScript/TypeScript runner right in your terminal.
JSComplete playground
This is a playground for JavaScript and React. You can use it to test simple code or prototype ideas. It requires a modern browser that understands ES2015 (ES6).
VSCode extensions Javascript REPL
Javascript REPL is a javascript playground for Visual Studio Code with live feedback(logs or errors) as you type, besides your code, in a log explorer, or in an output channel. It supports Javascript, TypeScript, CoffeeScript and it can be used for development in Node.js projects or with front-end frameworks like React, Vue, Angular, Svelte etc.

Unable to debug browser JavaScript with Visual Studio 2017 or 2019

I am trying to debug a Web app with some ASP.NET (vbhtml) components and some more regular HTML5 bits. It was built several years ago and makes extensive use of Knockout. Some of these parts are broken and I am trying to debug them.
The project includes an API (WebAPI 2) and some other stuff. It is not straightforward to separate out the HTML5 parts and debug them using VSCode, so I think I am stuck with using Visual Studio.
For a tantalizing few minutes two days ago I was able to set breakpoints, step through the Javascript code and find one problem. I am not sure what I did right. Since then I have been unable to do any debugging of the Javascript components. I have tried using Visual Studio 2017 and 2019.
I ran debugging with Chrome selected and script debugging enabled. As soon as the browser launched, the breakpoint got a yellow flag at its left hand end which showed a message: The breakpoint will not currently be hit. Breakpoint set but not yet bound.
The browser ran normally but the breakpoint was not hit. When the Inspect window was open I could see some stuff heppening but nothing relevant.
I set up a new "Browse With" entry in Visual Studio. I selected chrome.exe and added --remote-debugging-port=9222 in the Arguments field. Saved it and started debugging. After the browser opened, I got pop-up error message: Cannot connect to runtime process, timeout after 10000 ms - (reason: Cannot connect to the target: connect ECONNREFUSED 127.0.0.1:51772).
Every time this happens I get a different port number at the end. When I click OK, debugging stops and the browser window closes. I have made absolutely sure that Chrome is closed before starting debugging, to the extent of running a batch file that kills all Chrome processes.
After more searching I selected the Chrome debugging configuration and then Debug|Start Without Debugging. Chrome started OK. I then selected Attach to Process and selected the process. It all looked good but the breakpoint went inactive again with the "breakpoint will not currently be hit" message.
I have tried adding "debugger;" entries to the code. VS 2019 complains about them and they have no effect.
If I try debugging with IE11 and got similar results. Sometimes I got an error saying that another debugger was already connected although I had previously killed Chrome.
I am at a loss. Any clues would much appreciated.
Rob
The problem was definitely in the bundle configuration. In my case it is a file called BundleConfig.vb. It appears to bundle up JavaScript and css files to enable faster loading of the site rather than loading each of the files as a discrete HTTP request.
My file starts like this:
Imports System.Web.Optimization
Public Module BundleConfig
' For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
Public Sub RegisterBundles(ByVal bundles As BundleCollection)
bundles.Add(New ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-3.4.1.min.js",
"~/Scripts/jquery-ui-1.12.1.js"))
and ends like this:
BundleTable.EnableOptimizations = False 'Commented out 190601 to debug scripts
'BundleTable.EnableOptimizations = True
End Sub
End Module
If EnableOptimization is True you will not be able to debug any of the JavaScript with either Visual Studio or the debug tools in Chrome or IE. Comment it out and debugging becomes possible.

Replacing V8 version of Chrome with a Debug Build

I would like to see the assembly and byte code generated by v8, when it's embedded in chrome. The standalone version of d8 does not have DOM support, so it's not sufficient in this case.
Running './chrome --js-flags="--help"' shows that "--print-bytecode" option is supported in this v8 version, but "--print-code" is not.
More precisely, I would like to run chrome like this:
'./chrome -js-flags="--print-code"'
How can I replace the v8 version in google-chrome with a debug version that supports "--print-code"?
I'm using a 64bit linux os.
Thanks.
Google Chrome builds are linked statically, which means you can't easily replace V8 or any other component.
One option is to compile Chromium from scratch (which will take a few hours). When you do so, simply add v8_enable_disassembler = true to your GN args to enable disassembler support in V8 (which includes --print-code support). See the instructions at https://chromium.googlesource.com/chromium/src/+/master/docs/linux_build_instructions.md.
Another option is to download a Debug build of Chromium (which has disassembler support by default) from the continuous integration infrastructure. This isn't officially supported, but it's possible: go to https://ci.chromium.org/p/chromium/g/main/console, click the latest green box in the chromium.linux > debug > builder > 64 column, scroll down to the "package build" step and click the "download" link.
Warning: What both approaches have in common is that the resulting builds may be very buggy, they don't auto-update, and the sandbox probably isn't working out of the box. You should only use these builds for targeted testing, not for regular browsing.

Node.JS debugging with Eclipse and Chromium Dev Tools V8

Eclipse is a you-love-it or you-hate-it tool for editing Javascript files. For me, it's both.
Anyway, I often prefer the SPKET JS editor plugin for Eclipse over the default one because of small details like object knowledge and included file code completion.
However, when using the V8 debugger from Chrome Dev Tools for server-side JavaScript like Node.JS, it opens a third editor Chromium (from the browser) for code stepping.
I would like everything in one tab, so I tried opening my files with the JS editor from the V8 tools, but the name in the tab is now hidden (try editing multiple files this way) and a new one opens up on debugging anyway*.
(* Note that PHP debugging has a similar problem, but it opens a new instance from the same PHP editor)
Chromium JS editor | SPKET JS Editor | Eclipse JS Editor
Also, I don't know if this is node-specific or Eclipse-specific, but node --debug doesn't seam to do anything, no variable outlining, no breakpoints. Whereas node --debug-brk does as expected. So either Node.js is weird, Eclipse is, I've missed the point or I've set up debugging wrong.
Could anyone elaborate on debugging server-side JS in Eclipse and using the most complete JS editor, so that:
JS editor is aware of functions inside objects and separate files like SPKET (Often the case in modern implementations like Node.js) but preferably free for any use (like Chromium Dev Tools)
Eclipse keeps code and debugging in the same tab (if at all possible)
Tabs keep the name of the files (bug or wrong setting?)
I am running Eclipse Indigo 3.7.2 with Google Chrome Developer Tools SDK WIP + remote debugging + JSDT bridge and - if relevant - optionally SPKET 1.6.20 IDE, on Ubuntu 12.04 x64.
--edit--
At least I figured out where to put the breakpoints. Not in the editor, but in the debugger. Open the Project Explorer:
Window -> Show View -> Other... -> General -> Project Explorer
In Project Explorer -> Select your debug item -> Open proper JS file ->
THIS is where you want to add breakpoints.
ChromeDevTools by default has its own separate .js files for debugging. If you want to have debugger stepping in your files, you would need to set this up:
http://code.google.com/p/chromedevtools/wiki/FeatureDebugOnRealFiles

How can I profile my Node app to see where I'm using up memory and CPU resources?

My website, CompassionPit.com, is powered by Node.js. I have released the source code; it's hosted at GitHub. The app itself is running on a Linode with 768MB of RAM (I recently upgraded the server; it was at 512MB).
Recently I have been getting CPU usage notifications from Linode: we're increasingly often at 90%+ usage. I called Linode to see what I could do about upgrading my access to CPU resources, but apparently I'm okay for now, since if we max out to 100% then we can spill over into the next 3 cores (Linodes are 4 processor Xen instances).
How can I profile my Node app to see where I'm using up memory and CPU resources? I predict I'll soon need to restructure the application to be run by a multiple server setup, but I intuitively believe that proper profiling will lead to smarter architecture decisions. Please correct me if I'm wrong.
Node inspector can't profile node after version 0.6.x
The following plugin has been updated to work with new version of v8 (node 0.7.x +). It's the only one besides nodetime.com that is still working. It uses the actual webkit debugger:
https://github.com/c4milo/node-webkit-agent
It has very clear instructions as well.
I've had reasonable success using https://github.com/dannycoates/node-inspector for profiling. There's a setup guide at the bottom of the README file.
As of later versions of Node.js, the profiling part of node-inspector no longer functions. I've had reasonable success with --prof (http://code.google.com/p/v8/wiki/V8Profiler) and https://github.com/c4milo/node-webkit-agent as mentioned in the answer below.
As of v6.3.0, you can now run node --inspect your_script.js.
Node will print a URL to the console, which can be opened in Chrome, which will connect you to reveal a fully-functional Web Inspector that you can use to profile the Node process.
Run node --inspect --debug-brk to immediately pause execution (which is handy if you need to start a profiling session as soon as your application starts)

Categories