Johnson Duke

Johnson Duke

1583137446

Node.js debugging in VS Code

The Visual Studio Code editor has built-in debugging support for the Node.js runtime and can debug JavaScript, TypeScript, and many other languages that are transpiled into JavaScript. Setting up a project for Node.js debugging is usually straightforward with VS Code providing appropriate launch configuration defaults and snippets.

Note: If you are just getting started with VS Code, you can learn about general debugging features and creating launch.json configuration files in the Debugging topic.

This Node.js debugging document goes into more detail about configurations and features for more advanced debugging scenarios. You’ll find instruction for debugging with source maps, stepping over external code, doing remote debugging, and much more.

If you’d like to watch an introductory video, see Getting started with Node.js debugging:

Launch configuration attributes

Debugging configurations are stored in a launch.json file located in your workspace’s .vscode folder. An introduction into the creation and use of debugging configuration files is in the general Debugging topic.

Below is a reference on launch.json attributes specific to the Node.js debugger.

The following attributes are supported in launch configurations of type launch and attach:

These attributes are only available for launch configurations of request type launch:

  • program - an absolute path to the Node.js program to debug.
  • args - arguments passed to the program to debug. This attribute is of type array and expects individual arguments as array elements.
  • cwd - launch the program to debug in this directory.
  • runtimeExecutable - absolute path to the runtime executable to be used. Default is node. See section Launch configuration support for ‘npm’ and other tools.
  • runtimeArgs - optional arguments passed to the runtime executable.
  • runtimeVersion - if “nvm” (or “nvm-windows”) or “nvs” is used for managing Node.js versions, this attribute can be used to select a specific version of Node.js. See section Multi version support below.
  • env - optional environment variables. This attribute expects environment variables as a list of string typed key/value pairs.
  • envFile - optional path to a file containing environment variable definitions. See section Load environment variables from external file below.
  • console - kind of console to launch the program (internalConsole, integratedTerminal, externalTerminal). See section Node Console below.
  • outputCapture - if set to std, output from the process stdout/stderr will be shown in the Debug Console, instead of listening to output over the debug port. This is useful for programs or log libraries that write directly to the stdout/stderr streams instead of using console.* APIs.
  • autoAttachChildProcesses - track all subprocesses of debuggee and automatically attach to those that are launched in debug mode. See section Automatically attach debugger to Node.js subprocesses below.

This attribute is only available for launch configurations of request type attach:

  • processId - the debugger tries to attach to this process after having sent a USR1 signal. With this setting, the debugger can attach to an already running process that was not started in debug mode. When using the processId attribute the debug port is determined automatically based on the Node.js version (and the used protocol) and cannot be configured explicitly. So don’t specify a port attribute.

Launch configurations for common scenarios

You can trigger IntelliSense (Ctrl+Space) in your launch.json file to see launch configuration snippets for commonly used Node.js debugging scenarios.

Launch configuration snippets for Node.js

You can also bring up the snippets with the Add Configuration… button in the lower right of the launch.json editor window.

Add Configuration button

Here is the list of all snippets:

  • Launch Program: Launch a Node.js program in debug mode.
  • Launch via npm: Launch a Node.js program through an npm ‘debug’ script. If you have defined an npm debug script in your package.json, you can use this directly from your launch configuration. Make sure that the debug port used in the npm script, corresponds to the port specified in the snippet.
  • Attach: Attach to the debug port of a locally running Node.js program. Make sure that the Node.js program to debug has been started in debug mode and the debug port used is the same as the one specified in the snippet.
  • Attach to Remote Program: Attach to the debug port of a Node.js program running on the host specified by the address attribute. Make sure that the Node.js program to debug has been started in debug mode and the debug port used is the same as the one specified in the snippet. To help VS Code mapping source files between your workspace and the filesystem of the remote host, make sure to specify correct paths for the localRootand remoteRoot attributes.
  • Attach by Process ID: Open the process picker to select a node or gulp process for debugging. With this launch configuration, you can even attach to a node or gulp process that was not started in debug mode.
  • Nodemon Setup: Use nodemon to relaunch a debug session automatically whenever the JavaScript source has changed. Make sure that you have nodemon installed globally. Please note that terminating the debug session only terminates the program to debug, not nodemon itself. To terminate nodemon, press Ctrl+C in the Integrated Terminal.
  • Mocha Tests: Debug mocha tests in a test folder of your project. Make sure that your project has ‘mocha’ installed in its node_modules folder.
  • Yeoman generator: Debug a yeoman generator. The snippet asks you to specify the name of the generator. Make sure that your project has ‘yo’ installed in its node_modules folder and that your generated project has been installed for debugging by running npm link in the project folder.
  • Gulp task: Debug a gulp task. Make sure that your project has ‘gulp’ installed in its node_modules folder.
  • Electron Main: Debug the main Node.js process of an Electron application. The snippet assumes that the Electron executable has been installed inside the node_modules/.bin directory of the workspace.

Node console

By default, Node.js debug sessions launch the target in the internal VS Code Debug Console. Since the Debug Console does not support programs that need to read input from the console, you can enable either an external terminal or use the VS Code Integrated Terminal by setting the console attribute in your launch configuration to externalTerminal or integratedTerminal respectively. The default is internalConsole.

If an external terminal is used, you can configure which terminal program to use via the terminal.external.windowsExec, terminal.external.osxExec, and terminal.external.linuxExec settings.

Launch configuration support for ‘npm’ and other tools

Instead of launching the Node.js program directly with node, you can use ‘npm’ scripts or other task runner tools directly from a launch configuration:

  • Any program available on the PATH (for example ‘npm’, ‘mocha’, ‘gulp’, etc.) can be used for the runtimeExecutable attribute and arguments can be passed via runtimeArgs.
  • You do not have to set the program attribute if your npm script or other tool implicitly specifies the program to launch.
  • If you specify a debug port via the port attribute, VS Code will not automatically add the --inspect-brk=nnnn attribute because the debug port is typically specified by the npm script or other tool as well.

Let’s look at an ‘npm’ example. If your package.json has a ‘debug’ script, for example:

  "scripts": {
    "debug": "node --nolazy --inspect-brk=9229 myProgram.js"
  },

the corresponding launch configuration would look like this:

{
  "name": "Launch via npm",
  "type": "node",
  "request": "launch",
  "cwd": "${workspaceFolder}",
  "runtimeExecutable": "npm",
  "runtimeArgs": ["run-script", "debug"],
  "port": 9229
}

Multi version support

If you are using ‘nvm’ (or ‘nvm-windows’) to manage your Node.js versions, it is possible to specify a runtimeVersion attribute in a launch configuration for selecting a specific version of Node.js:

{
  "type": "node",
  "request": "launch",
  "name": "Launch test",
  "runtimeVersion": "7.10.1",
  "program": "${workspaceFolder}/test.js"
}

If you are using ‘nvs’ to manage your Node.js versions, it is possible to use runtimeVersion attribute to select a specific version of Node.js:

{
  "type": "node",
  "request": "launch",
  "name": "Launch test",
  "runtimeVersion": "chackracore/8.9.4/x64",
  "program": "${workspaceFolder}/test.js"
}

Make sure to have those Node.js versions installed that you want to use with the runtimeVersion attribute as the feature will not download and install the version itself. So you will have to run something like nvm install 7.10.1 or nvs add 7.10.1 from the integrated terminal if you plan to add "runtimeVersion": "7.10.1" to your launch configuration.

Note: If VS Code detects that “nvs” is installed, it does not fall back to “nvm” if a specific Node.js version cannot be found in “nvs”. Using both “nvs” and “nvm” at the same time is not supported.

Load environment variables from external file (node)

The VS Code Node debugger supports loading environment variables from a file and passing them to the Node.js runtime. To use this feature, add an attribute envFile to your launch configuration and specify the absolute path to the file containing the environment variables:

   //...
   "envFile": "${workspaceFolder}/.env",
   "env": { "USER": "john doe" }
   //...

Any environment variable specified in the env dictionary will override variables loaded from the file.

Here is an example of an .env file:

USER=doe
PASSWORD=abc123

# a comment

# an empty value:
empty=

# new lines expanded in quoted strings:
lines="foo\nbar"

Attaching to Node.js

If you want to attach the VS Code debugger to a Node.js program, launch Node.js in VS Code’s integrated terminal as follows:

node --inspect program.js

or if the program should not start running but must wait for the debugger to attach:

node --inspect-brk program.js

Now you have three options for attaching the debugger to your program:

  • have VS Code automatically attach to the program, or
  • open a “process picker” that lists all potential candidate processes and let you pick one, or
  • create an “attach” configuration that explicitly specifies all configuration options and then press F5.

Let’s go through these options in detail:

Auto Attach Feature

If the Auto Attach feature is enabled, the Node debugger automatically attaches to Node.js processes that have been launched in debug mode from VS Code’s Integrated Terminal.

To enable the feature, either use the Toggle Auto Attach action or, if the Node debugger is already activated, use the Auto Attach Status Bar item.

After enabling Auto Attach the debugger should attach to your program within a second:

Auto Attach

Whether or not a process is in “debug mode” is determined by analyzing the program arguments. Currently, we detect the patterns --inspect, --inspect-brk, --inspect-port, --debug, --debug-brk, --debug-port (all optionally followed by a ‘=’ and a port number).

Note: this feature does not (yet) work for terminal multiplexers like tmux (where launched processes are not children of VS Code’s integrated terminal).

Attach to Node Process action

The Attach to Node Process action opens a Quick Pick menu that lists all potential processes that are available to the Node.js debugger:

Node.js Process picker

The individual processes listed in the picker show the debug port and the detected protocol in addition to the process ID. You should find your Node.js process in that list and after selecting it, the Node.js debugger tries to attach to it.

In addition to Node.js processes, the picker also shows other programs that were launched with one of the various forms of --debug or --inspect arguments. This makes it possible to attach to Electron’s or VS Code’s helper processes.

Setting up an “Attach” configuration

This option requires more work but in contrast to the previous two options it allows you to configure various debug configuration options explicitly.

The simplest “attach” configuration looks like this:

{
  "name": "Attach to Process",
  "type": "node",
  "request": "attach",
  "port": 9229
}

The port 9229 is the default debug port of the --inspect and --inspect-brk options. To use a different port (for example 12345), add it to the options like this: --inspect=12345 and --inspect-brk=12345 and change the port attribute in the launch configuration accordingly.

If you want to attach to a Node.js process that hasn’t been started in debug mode, you can do this by specifying the process ID of the Node.js process as a string:

{
  "name": "Attach to Process",
  "type": "node",
  "request": "attach",
  "processId": "53426"
}

Since it is a bit laborious to repeatedly find the process ID and enter it in the launch configuration, Node debug supports a command variable PickProcess that binds to the process picker (from above) and that lets you conveniently pick the process from a list of Node.js processes.

By using the PickProcess variable the launch configuration looks like this:

{
  "name": "Attach to Process",
  "type": "node",
  "request": "attach",
  "processId": "${command:PickProcess}"
}

Stop debugging

Using the Debug: Stop action (available in the Debug toolbar or via the Command Palette) stops the debug session.

If the debug session was started in “attach” mode (and the red terminate button in the Debug toolbar shows a superimposed “plug”), pressing Stop disconnects the Node.js debugger from the debuggee that then continues execution.

If the debug session is in “launch” mode, pressing Stop does the following:

  1. When pressing Stop for the first time, the debuggee is requested to shutdown gracefully by sending a SIGINT signal. The debuggee is free to intercept this signal and clean up anything as necessary and then shut down. If there are no breakpoints (or problems) in that shutdown code, the debuggee and the debug session will terminate.

  2. However if the debugger hits a breakpoint in the shutdown code or if the debuggee does not terminate properly by itself, then the debug session will not end. In this case, pressing Stop again will force terminate the debuggee and its child processes (SIGKILL).

So if you see that a debug session doesn’t end when you press the red Stop button, then press the button again to force a shutdown of the debuggee.

Note that on the Windows operating system, pressing Stop always forcibly kills the debuggee and its child processes.

Source maps

The Node.js debugger of VS Code supports JavaScript source maps that help debugging of transpiled languages, for example, TypeScript or minified/uglified JavaScript. With source maps, it is possible to single step through or set breakpoints in the original source. If no source map exists for the original source or if the source map is broken and cannot successfully map between the source and the generated JavaScript, then breakpoints show up as unverified (gray hollow circles).

Source maps can be generated with two kinds of inlining:

  • Inlined source maps: the generated JavaScript file contains the source map as a data URI at the end (instead of referencing the source map through a file URI).
  • Inlined source: the source map contains the original source (instead of referencing the source through a path).

VS Code supports both the inlined source maps and the inlined source.

The source map feature is controlled by the sourceMaps attribute that defaults to true. This means that node debugging always tries to use source maps (if it can find any) and as a consequence, you can even specify a source file (for example, app.ts) with the program attribute.

If you need to disable source maps for some reason, you can set the sourceMaps attribute to false.

If the generated (transpiled) JavaScript files do not live next to their source but in a separate directory, you must help the VS Code debugger locating them by setting the outFiles attribute. This attribute takes multiple glob patterns for including and excluding files from the set of generated JavaScript files. Whenever you set a breakpoint in the original source, VS Code tries to find the generated JavaScript code in the files specified by outFiles.

Since source maps are not automatically created, you must configure the transpiler you are using to create them. For TypeScript this can be done in the following way:

tsc --sourceMap --outDir bin app.ts

This is the corresponding launch configuration for a TypeScript program:

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Launch TypeScript",
      "type": "node",
      "request": "launch",
      "program": "app.ts",
      "outFiles": ["${workspaceFolder}/bin/**/*.js"]
    }
  ]
}

Smart stepping

With the smartStep attribute set to true in a launch configuration, VS Code will automatically skip ‘uninteresting code’ when stepping through code in the debugger. ‘Uninteresting code’ is code that is generated by a transpiling process but is not covered by a source map so it does not map back to the original source. This code gets in your way when stepping through source code in the debugger because it makes the debugger switch between the original source code and generated code that you are not really interested in. smartStep will automatically step through code not covered by a source map until it reaches a location that is covered by a source map again.

This is especially useful for cases like async/await downcompilation in TypeScript, where the compiler injects helper code that is not covered by a source map.

Please note that the smartStep feature only applies to JavaScript code that was generated from source and therefore has a source map. For JavaScript without sources, the smart stepping option has no effect.

JavaScript source map tips

A common issue when debugging with source maps is that you’ll set a breakpoint, and it will turn gray. If you hover the cursor over it, you’ll see the message, "Breakpoint ignored because generated code not found (source map problem?)". What now? There are a range of issues that can lead to this. First, a quick explanation of how the Node debug adapter handles source maps.

When you set a breakpoint in app.ts, the debug adapter has to figure out the path to app.js, the transpiled version of your TypeScript file, which is what is actually running in Node. But, there is not a straightforward way to figure this out starting from the .ts file. Instead, the debug adapter uses the outFiles attribute in the launch.json to find all the transpiled .js files, and parses them for a source map, which contains the locations of its associated .ts files.

When you build your app.ts file in TypeScript with source maps enabled, it either produces an app.js.map file, or a source map inlined as a base64-encoded string in a comment at the bottom of the app.js file. To find the .ts files associated with this map, the debug adapter looks at two properties in the source map, sources, and sourceRoot. sourceRoot is optional - if present, it is prepended to each path in sources, which is an array of paths. The result is an array of absolute or relative paths to .ts files. Relative paths are resolved relative to the source map.

Finally, the debug adapter searches for the full path of app.ts in this resulting list of .ts files. If there’s a match, it has found the source map file to use when mapping app.ts to app.js. If there is no match, then it can’t bind the breakpoint, and it will turn gray.

Here are some things to try when your breakpoints turn gray:

  • Do you have "sourceMaps": false in your launch.json?
  • Did you build with source maps enabled? Are there .js.map files, or inlined source maps in your .js files?
  • Did you set the outFiles property in your launch.json? It should be a glob pattern for an absolute path that matches your .js files.
  • Try the ‘inspector’ protocol implementation. It can handle some more of the more complex source map cases.
  • Are the sourceRoot and sources properties in your source map correct? Can they be combined to get the correct path to the .ts file?
  • Are you using Webpack? By default, it outputs paths with a webpack:/// prefix, which the debug adapter can’t resolve. You can change this in your Webpack configuration with the devtoolModuleFilenameTemplate option, or try using the ‘inspector’ protocol, which provides some extra options for resolving these paths.
  • Have you opened the folder in VS Code with the incorrect case? It’s possible to open folder foo/ from the command line like code FOO in which case source maps may not be resolved correctly.
  • Try searching for help with your particular setup on Stack Overflow or by filing an issue on GitHub.
  • Try adding a debugger statement. If it breaks into the .ts file there, but breakpoints at that spot don’t bind, that is useful information to include with a GitHub issue.

Remote debugging

The Node.js debugger supports remote debugging for versions of Node.js >= 4.x. Specify a remote host via the address attribute. Here is an example:

{
  "type": "node",
  "request": "attach",
  "name": "Attach to remote",
  "address": "TCP/IP address of process to be debugged",
  "port": "9229"
}

By default, VS Code will stream the debugged source from the remote Node.js folder to the local VS Code and show it in a read-only editor. You can step through this code, but cannot modify it. If you want VS Code to open the editable source from your workspace instead, you can setup a mapping between the remote and local locations. A localRoot and a remoteRoot attribute can be used to map paths between a local VS Code project and a (remote) Node.js folder. This works even locally on the same system or across different operating systems. Whenever a code path needs to be converted from the remote Node.js folder to a local VS Code path, the remoteRoot path is stripped off the path and replaced by localRoot. For the reverse conversion, the localRoot path is replaced by the remoteRoot.

{
  "type": "node",
  "request": "attach",
  "name": "Attach to remote",
  "address": "TCP/IP address of process to be debugged",
  "port": "9229",
  "localRoot": "${workspaceFolder}",
  "remoteRoot": "C:\\Users\\username\\project\\server"
}

Two frequently used applications of remote debugging are:

  • debugging Node.js in a Docker container:

If you are running Node.js inside a Docker container, you can use the approach from above to debug Node.js inside the Docker container and map back the remote source to files in your workspace. We have created a “recipe” on GitHub that walks you through on how to set this up Node.js in Docker with TypeScript.

  • debugging Node.js in the Windows Subsystem for Linux (WSL):

If you want to run Node.js in the Windows Subsystem for Linux (WSL), you can use the approach from above as well. However, to make this even simpler, we’ve introduced a useWSL flag to automatically configure everything so that Node.js runs in the Linux subsystem and source is mapped to files in your workspace.

Here is the simplest debug configuration for debugging hello.js in WSL:

```
{
  "type": "node",
  "request": "launch",
  "name": "Launch in WSL",
  "useWSL": true,
  "program": "${workspaceFolder}/hello.js"
}
```

Please note: With the arrival of the Remote - WSL extension, VS Code got universal support for Windows Subsystem for Linux (WSL). Consequently, the useWSL debug configuration attribute has been deprecated and support for it will be dropped soon. For more details, please see our Developing in WSL documentation.

Access Loaded Scripts

If you need to set a breakpoint in a script that is not part of your workspace and therefore cannot be easily located and opened through normal VS Code file browsing, you can access the loaded scripts via the LOADED SCRIPTS view in the debug viewlet:

Loaded Scripts Explorer

Alternatively, you can use the Debug: Open Loaded Script action (Ctrl+F4) which opens a Quick Pick, where you can filter and select the script to open.

Scripts are loaded into a read-only editor where you can set breakpoints. These breakpoints are remembered across debug sessions but you only have access to the script content while a debug session is running.

Restarting debug sessions automatically when source is edited

The restart attribute of a launch configuration controls whether the Node.js debugger automatically restarts after the debug session has ended. This feature is useful if you use nodemon to restart Node.js on file changes. Setting the launch configuration attribute restart to true makes the node debugger automatically try to reattach to Node.js after Node.js has terminated.

If you have started your program server.js via nodemon on the command line like this:

nodemon --inspect server.js

you can attach the VS Code debugger to it with the following launch configuration:

{
  "name": "Attach to node",
  "type": "node",
  "request": "attach",
  "restart": true,
  "port": 9229
}

Alternatively you can start your program server.js via nodemon directly with a launch config and attach the VS Code debugger:

{
  "name": "Launch server.js via nodemon",
  "type": "node",
  "request": "launch",
  "runtimeExecutable": "nodemon",
  "program": "${workspaceFolder}/server.js",
  "restart": true,
  "console": "integratedTerminal",
  "internalConsoleOptions": "neverOpen"
}

Tip: Pressing the Stop button stops the debug session and disconnects from Node.js, but nodemon (and Node.js) will continue to run. To stop nodemon, you will have to kill it from the command line (which is easily possible if you use the integratedTerminal as shown above).

Tip: In case of syntax errors, nodemon will not be able to start Node.js successfully until the error has been fixed. In this case, VS Code will continue trying to attach to Node.js but eventually give up (after 10 seconds). To avoid this, you can increase the timeout by adding a timeout attribute with a larger value (in milliseconds).

Automatically attach debugger to Node.js subprocesses

The Node debugger has a mechanism that tracks all subprocesses of a debuggee and tries to automatically attach to those processes that are launched in debug mode. This feature simplifies debugging of programs that fork or spawn Node.js processes like programs based on the “cluster” node module:

Auto Attach shown with Cluster Example

The feature is enabled by setting the launch config attribute autoAttachChildProcesses to true:

{
  "type": "node",
  "request": "launch",
  "name": "Cluster",
  "program": "${workspaceFolder}/cluster.js",
  "autoAttachChildProcesses": true
}

Tip: In order to be able to track the subprocesses, we need the process ID of the parent. For this we require that the main debuggee launched from the launch config is a Node.js process and we use an “evaluate” to find its process ID.

Tip: Whether a process is in debug mode is guessed by analyzing the program arguments. Currently we detect the patterns --inspect, --inspect-brk, --inspect-port, --debug, --debug-brk, --debug-port (all optionally followed by a = and a port number).

Restart frame (node)

The Node debugger supports restarting execution at a stack frame. This can be useful in situations where you have found a problem in your source code and you want to rerun a small portion of the code with modified input values. Stopping and then restarting the full debug session can be very time-consuming. The Restart Frame action allows you to reenter the current function after you have changed variables with the Set Value action:

restart frame

Note that Restart Frame won’t unroll any state changes, so it may not always work as expected.

Make sure to use a Node.js version >= 5.11 since earlier versions do not work in all situations.

Breakpoints

Function breakpoints

The Node.js debugger only supports function breakpoints when the “legacy” protocol is used (that is when targeting Node.js < 8.0 versions). In addition, be aware of the following limitations when using function breakpoints:

  • Function breakpoints only work for global, non-native functions.
  • Function breakpoints can only be created if the function has been defined (and has been seen by the debugger).

function breakpoint

Breakpoint hit counts

The ‘hit count condition’ controls how many times a breakpoint needs to be hit before it will ‘break’ execution. The hit count syntax supported by the Node.js debugger is either an integer or one of the operators <, <=, ==, >, >=, % followed by an integer.

Some examples:

  • >10 break always after 10 hits
  • <3 break on the first two hits only
  • 10 same as >=10
  • %2 break on every other hit

Breakpoint validation

For performance reasons, Node.js parses the functions inside JavaScript files lazily on first access. As a consequence, breakpoints don’t work in source code areas that haven’t been seen (parsed) by Node.js.

Since this behavior is not ideal for debugging, VS Code passes the --nolazy option to Node.js automatically. This prevents the delayed parsing and ensures that breakpoints can be validated before running the code (so they no longer “jump”).

Since the --nolazy option might increase the start-up time of the debug target significantly, you can easily opt out by passing a --lazy as a runtimeArgs attribute.

When doing so, you will find that some of your breakpoints don’t “stick” to the line requested but instead “jump” for the next possible line in already-parsed code. To avoid confusion, VS Code always shows breakpoints at the location where Node.js thinks the breakpoint is. In the BREAKPOINTS section, these breakpoints are shown with an arrow between requested and actual line number:

Breakpoints View

This breakpoint validation occurs when a session starts and the breakpoints are registered with Node.js, or when a session is already running and a new breakpoint is set. In this case, the breakpoint may “jump” to a different location. After Node.js has parsed all the code (for example, by running through it), breakpoints can be easily reapplied to the requested locations with the Reapply button in the BREAKPOINTS section header. This should make the breakpoints “jump back” to the requested location.

Breakpoint Actions

Skipping uninteresting code (node, chrome)

VS Code Node.js debugging has a feature to avoid source code that you don’t want to step through (AKA ‘Just My Code’). This feature can be enabled with the skipFiles attribute in your launch configuration. skipFiles is an array of glob patterns for script paths to skip.

For example, using:

  "skipFiles": [
    "${workspaceFolder}/node_modules/**/*.js",
    "${workspaceFolder}/lib/**/*.js"
  ]

all code in the node_modules and lib folders in your project will be skipped.

Built-in core modules of Node.js can be referred to by the ‘magic name’ <node_internals> in a glob pattern. The following example skips all internal modules:

  "skipFiles": [
     "<node_internals>/**/*.js"
   ]

The exact ‘skipping’ rules are as follows:

  • If you step into a skipped file, you won’t stop there - you will stop on the next executed line that is not in a skipped file.
  • If you have set the option to break on thrown exceptions, then you won’t break on exceptions thrown from skipped files.
  • If you set a breakpoint in a skipped file, you will stop at that breakpoint, and you will be able to step through it until you step out of it, at which point normal skipping behavior will resume.

Skipped source is shown in a ‘dimmed’ style in the CALL STACK view:

Skipped source is dimmed in call stack view

Hovering over the dimmed entries explains why the stack frame is dimmed.

A context menu item on the call stack, Toggle skipping this file enables you to easily skip a file at runtime without adding it to your launch config. This option only persists for the current debugging session. You can also use it to stop skipping a file that is skipped by the skipFiles option in your launch config.

Note: The legacy protocol debugger supports negative glob patterns, but they must follow a positive pattern: positive patterns add to the set of skipped files, while negative patterns subtract from that set.

In the following (legacy protocol-only) example all but a ‘math’ module is skipped:

"skipFiles": [
    "${workspaceFolder}/node_modules/**/*.js",
    "!${workspaceFolder}/node_modules/math/**/*.js"
]

Note: The legacy protocol debugger has to emulate the skipFiles feature because the V8 Debugger Protocol does not support it natively. This might result in slow stepping performance.

Supported Node-like runtimes

Since the VS Code Node.js debugger communicates to the Node.js runtimes through wire protocols, the set of supported runtimes is determined by all runtimes supporting the wire protocols.

Today two wire protocols exist:

  • legacy: the original V8 Debugger Protocol, which is currently supported by older runtimes.
  • inspector: the new V8 Inspector Protocol is exposed via the --inspect flag in Node.js versions >= 6.3. It addresses most of the limitations and scalability issues of the legacy protocol.

Currently these protocols are supported by specific version ranges of the following runtimes:

Node.js debugging in VS Code

Although it appears to be possible that the VS Code Node.js debugger picks the best protocol always automatically, we’ve decided for a ‘pessimistic approach’ with an explicit launch configuration attribute protocol and the following values:

  • auto: tries to automatically detect the protocol used by the targeted runtime. For configurations of request type launch and if no runtimeExecutable is specified, we try to determine the version by running node from the PATH with an --version argument. If the node version is >= 8.0, the new ‘inspector’ protocol is used. For configurations of request type ‘attach’, we try to connect with the new protocol and if this works, we use the ‘inspector’ protocol. We only switch to the new ‘inspector’ protocol for versions >= 6.9 because of severe problems in earlier versions.
  • inspector: forces the node debugger to use the ‘inspector’ protocol-based implementation. This is supported by node versions >= 6.3 and Electron versions >= 1.7.4.
  • legacy: forces the node debugger to use the ‘legacy’ protocol-based implementation. This is supported by node versions < v8.0 and Electron versions < 1.7.4.

Starting with VS Code 1.11, the default value for the protocol attribute is auto.

If your runtime supports both protocols, here are a few additional reasons for using the inspector protocol over legacy:

  • It can be more stable when debugging very large JavaScript objects. The legacy protocol can become painfully slow when sending large values between the client and server.
  • If you are using an ES6 Proxy in your app, you can prevent a Node v7+ runtime from crashing when being debugged via the inspector protocol. This issue is tracked in Microsoft/vscode#12749.
  • Debugging via the inspector protocol can handle some trickier source map setups. If you have trouble setting breakpoints in source mapped files, try using inspector.

We try to keep feature parity between both protocol implementations but this becomes more and more difficult because the technology underlying legacy is deprecated whereas the new inspector evolves quickly. For this reason, we specify the supported protocols if a feature is not supported by both legacy and inspector.

#nodejs #vscode #webdev #javascript

What is GEEK

Buddha Community

Node.js debugging in VS Code

NBB: Ad-hoc CLJS Scripting on Node.js

Nbb

Not babashka. Node.js babashka!?

Ad-hoc CLJS scripting on Node.js.

Status

Experimental. Please report issues here.

Goals and features

Nbb's main goal is to make it easy to get started with ad hoc CLJS scripting on Node.js.

Additional goals and features are:

  • Fast startup without relying on a custom version of Node.js.
  • Small artifact (current size is around 1.2MB).
  • First class macros.
  • Support building small TUI apps using Reagent.
  • Complement babashka with libraries from the Node.js ecosystem.

Requirements

Nbb requires Node.js v12 or newer.

How does this tool work?

CLJS code is evaluated through SCI, the same interpreter that powers babashka. Because SCI works with advanced compilation, the bundle size, especially when combined with other dependencies, is smaller than what you get with self-hosted CLJS. That makes startup faster. The trade-off is that execution is less performant and that only a subset of CLJS is available (e.g. no deftype, yet).

Usage

Install nbb from NPM:

$ npm install nbb -g

Omit -g for a local install.

Try out an expression:

$ nbb -e '(+ 1 2 3)'
6

And then install some other NPM libraries to use in the script. E.g.:

$ npm install csv-parse shelljs zx

Create a script which uses the NPM libraries:

(ns script
  (:require ["csv-parse/lib/sync$default" :as csv-parse]
            ["fs" :as fs]
            ["path" :as path]
            ["shelljs$default" :as sh]
            ["term-size$default" :as term-size]
            ["zx$default" :as zx]
            ["zx$fs" :as zxfs]
            [nbb.core :refer [*file*]]))

(prn (path/resolve "."))

(prn (term-size))

(println (count (str (fs/readFileSync *file*))))

(prn (sh/ls "."))

(prn (csv-parse "foo,bar"))

(prn (zxfs/existsSync *file*))

(zx/$ #js ["ls"])

Call the script:

$ nbb script.cljs
"/private/tmp/test-script"
#js {:columns 216, :rows 47}
510
#js ["node_modules" "package-lock.json" "package.json" "script.cljs"]
#js [#js ["foo" "bar"]]
true
$ ls
node_modules
package-lock.json
package.json
script.cljs

Macros

Nbb has first class support for macros: you can define them right inside your .cljs file, like you are used to from JVM Clojure. Consider the plet macro to make working with promises more palatable:

(defmacro plet
  [bindings & body]
  (let [binding-pairs (reverse (partition 2 bindings))
        body (cons 'do body)]
    (reduce (fn [body [sym expr]]
              (let [expr (list '.resolve 'js/Promise expr)]
                (list '.then expr (list 'clojure.core/fn (vector sym)
                                        body))))
            body
            binding-pairs)))

Using this macro we can look async code more like sync code. Consider this puppeteer example:

(-> (.launch puppeteer)
      (.then (fn [browser]
               (-> (.newPage browser)
                   (.then (fn [page]
                            (-> (.goto page "https://clojure.org")
                                (.then #(.screenshot page #js{:path "screenshot.png"}))
                                (.catch #(js/console.log %))
                                (.then #(.close browser)))))))))

Using plet this becomes:

(plet [browser (.launch puppeteer)
       page (.newPage browser)
       _ (.goto page "https://clojure.org")
       _ (-> (.screenshot page #js{:path "screenshot.png"})
             (.catch #(js/console.log %)))]
      (.close browser))

See the puppeteer example for the full code.

Since v0.0.36, nbb includes promesa which is a library to deal with promises. The above plet macro is similar to promesa.core/let.

Startup time

$ time nbb -e '(+ 1 2 3)'
6
nbb -e '(+ 1 2 3)'   0.17s  user 0.02s system 109% cpu 0.168 total

The baseline startup time for a script is about 170ms seconds on my laptop. When invoked via npx this adds another 300ms or so, so for faster startup, either use a globally installed nbb or use $(npm bin)/nbb script.cljs to bypass npx.

Dependencies

NPM dependencies

Nbb does not depend on any NPM dependencies. All NPM libraries loaded by a script are resolved relative to that script. When using the Reagent module, React is resolved in the same way as any other NPM library.

Classpath

To load .cljs files from local paths or dependencies, you can use the --classpath argument. The current dir is added to the classpath automatically. So if there is a file foo/bar.cljs relative to your current dir, then you can load it via (:require [foo.bar :as fb]). Note that nbb uses the same naming conventions for namespaces and directories as other Clojure tools: foo-bar in the namespace name becomes foo_bar in the directory name.

To load dependencies from the Clojure ecosystem, you can use the Clojure CLI or babashka to download them and produce a classpath:

$ classpath="$(clojure -A:nbb -Spath -Sdeps '{:aliases {:nbb {:replace-deps {com.github.seancorfield/honeysql {:git/tag "v2.0.0-rc5" :git/sha "01c3a55"}}}}}')"

and then feed it to the --classpath argument:

$ nbb --classpath "$classpath" -e "(require '[honey.sql :as sql]) (sql/format {:select :foo :from :bar :where [:= :baz 2]})"
["SELECT foo FROM bar WHERE baz = ?" 2]

Currently nbb only reads from directories, not jar files, so you are encouraged to use git libs. Support for .jar files will be added later.

Current file

The name of the file that is currently being executed is available via nbb.core/*file* or on the metadata of vars:

(ns foo
  (:require [nbb.core :refer [*file*]]))

(prn *file*) ;; "/private/tmp/foo.cljs"

(defn f [])
(prn (:file (meta #'f))) ;; "/private/tmp/foo.cljs"

Reagent

Nbb includes reagent.core which will be lazily loaded when required. You can use this together with ink to create a TUI application:

$ npm install ink

ink-demo.cljs:

(ns ink-demo
  (:require ["ink" :refer [render Text]]
            [reagent.core :as r]))

(defonce state (r/atom 0))

(doseq [n (range 1 11)]
  (js/setTimeout #(swap! state inc) (* n 500)))

(defn hello []
  [:> Text {:color "green"} "Hello, world! " @state])

(render (r/as-element [hello]))

Promesa

Working with callbacks and promises can become tedious. Since nbb v0.0.36 the promesa.core namespace is included with the let and do! macros. An example:

(ns prom
  (:require [promesa.core :as p]))

(defn sleep [ms]
  (js/Promise.
   (fn [resolve _]
     (js/setTimeout resolve ms))))

(defn do-stuff
  []
  (p/do!
   (println "Doing stuff which takes a while")
   (sleep 1000)
   1))

(p/let [a (do-stuff)
        b (inc a)
        c (do-stuff)
        d (+ b c)]
  (prn d))
$ nbb prom.cljs
Doing stuff which takes a while
Doing stuff which takes a while
3

Also see API docs.

Js-interop

Since nbb v0.0.75 applied-science/js-interop is available:

(ns example
  (:require [applied-science.js-interop :as j]))

(def o (j/lit {:a 1 :b 2 :c {:d 1}}))

(prn (j/select-keys o [:a :b])) ;; #js {:a 1, :b 2}
(prn (j/get-in o [:c :d])) ;; 1

Most of this library is supported in nbb, except the following:

  • destructuring using :syms
  • property access using .-x notation. In nbb, you must use keywords.

See the example of what is currently supported.

Examples

See the examples directory for small examples.

Also check out these projects built with nbb:

API

See API documentation.

Migrating to shadow-cljs

See this gist on how to convert an nbb script or project to shadow-cljs.

Build

Prequisites:

  • babashka >= 0.4.0
  • Clojure CLI >= 1.10.3.933
  • Node.js 16.5.0 (lower version may work, but this is the one I used to build)

To build:

  • Clone and cd into this repo
  • bb release

Run bb tasks for more project-related tasks.

Download Details:
Author: borkdude
Download Link: Download The Source Code
Official Website: https://github.com/borkdude/nbb 
License: EPL-1.0

#node #javascript

Hire Dedicated Node.js Developers - Hire Node.js Developers

If you look at the backend technology used by today’s most popular apps there is one thing you would find common among them and that is the use of NodeJS Framework. Yes, the NodeJS framework is that effective and successful.

If you wish to have a strong backend for efficient app performance then have NodeJS at the backend.

WebClues Infotech offers different levels of experienced and expert professionals for your app development needs. So hire a dedicated NodeJS developer from WebClues Infotech with your experience requirement and expertise.

So what are you waiting for? Get your app developed with strong performance parameters from WebClues Infotech

For inquiry click here: https://www.webcluesinfotech.com/hire-nodejs-developer/

Book Free Interview: https://bit.ly/3dDShFg

#hire dedicated node.js developers #hire node.js developers #hire top dedicated node.js developers #hire node.js developers in usa & india #hire node js development company #hire the best node.js developers & programmers

Aria Barnes

Aria Barnes

1622719015

Why use Node.js for Web Development? Benefits and Examples of Apps

Front-end web development has been overwhelmed by JavaScript highlights for quite a long time. Google, Facebook, Wikipedia, and most of all online pages use JS for customer side activities. As of late, it additionally made a shift to cross-platform mobile development as a main technology in React Native, Nativescript, Apache Cordova, and other crossover devices. 

Throughout the most recent couple of years, Node.js moved to backend development as well. Designers need to utilize a similar tech stack for the whole web project without learning another language for server-side development. Node.js is a device that adjusts JS usefulness and syntax to the backend. 

What is Node.js? 

Node.js isn’t a language, or library, or system. It’s a runtime situation: commonly JavaScript needs a program to work, however Node.js makes appropriate settings for JS to run outside of the program. It’s based on a JavaScript V8 motor that can run in Chrome, different programs, or independently. 

The extent of V8 is to change JS program situated code into machine code — so JS turns into a broadly useful language and can be perceived by servers. This is one of the advantages of utilizing Node.js in web application development: it expands the usefulness of JavaScript, permitting designers to coordinate the language with APIs, different languages, and outside libraries.

What Are the Advantages of Node.js Web Application Development? 

Of late, organizations have been effectively changing from their backend tech stacks to Node.js. LinkedIn picked Node.js over Ruby on Rails since it took care of expanding responsibility better and decreased the quantity of servers by multiple times. PayPal and Netflix did something comparative, just they had a goal to change their design to microservices. We should investigate the motivations to pick Node.JS for web application development and when we are planning to hire node js developers. 

Amazing Tech Stack for Web Development 

The principal thing that makes Node.js a go-to environment for web development is its JavaScript legacy. It’s the most well known language right now with a great many free devices and a functioning local area. Node.js, because of its association with JS, immediately rose in ubiquity — presently it has in excess of 368 million downloads and a great many free tools in the bundle module. 

Alongside prevalence, Node.js additionally acquired the fundamental JS benefits: 

  • quick execution and information preparing; 
  • exceptionally reusable code; 
  • the code is not difficult to learn, compose, read, and keep up; 
  • tremendous asset library, a huge number of free aides, and a functioning local area. 

In addition, it’s a piece of a well known MEAN tech stack (the blend of MongoDB, Express.js, Angular, and Node.js — four tools that handle all vital parts of web application development). 

Designers Can Utilize JavaScript for the Whole Undertaking 

This is perhaps the most clear advantage of Node.js web application development. JavaScript is an unquestionable requirement for web development. Regardless of whether you construct a multi-page or single-page application, you need to know JS well. On the off chance that you are now OK with JavaScript, learning Node.js won’t be an issue. Grammar, fundamental usefulness, primary standards — every one of these things are comparable. 

In the event that you have JS designers in your group, it will be simpler for them to learn JS-based Node than a totally new dialect. What’s more, the front-end and back-end codebase will be basically the same, simple to peruse, and keep up — in light of the fact that they are both JS-based. 

A Quick Environment for Microservice Development 

There’s another motivation behind why Node.js got famous so rapidly. The environment suits well the idea of microservice development (spilling stone monument usefulness into handfuls or many more modest administrations). 

Microservices need to speak with one another rapidly — and Node.js is probably the quickest device in information handling. Among the fundamental Node.js benefits for programming development are its non-obstructing algorithms.

Node.js measures a few demands all at once without trusting that the first will be concluded. Many microservices can send messages to one another, and they will be gotten and addressed all the while. 

Versatile Web Application Development 

Node.js was worked in view of adaptability — its name really says it. The environment permits numerous hubs to run all the while and speak with one another. Here’s the reason Node.js adaptability is better than other web backend development arrangements. 

Node.js has a module that is liable for load adjusting for each running CPU center. This is one of numerous Node.js module benefits: you can run various hubs all at once, and the environment will naturally adjust the responsibility. 

Node.js permits even apportioning: you can part your application into various situations. You show various forms of the application to different clients, in light of their age, interests, area, language, and so on. This builds personalization and diminishes responsibility. Hub accomplishes this with kid measures — tasks that rapidly speak with one another and share a similar root. 

What’s more, Node’s non-hindering solicitation handling framework adds to fast, letting applications measure a great many solicitations. 

Control Stream Highlights

Numerous designers consider nonconcurrent to be one of the two impediments and benefits of Node.js web application development. In Node, at whatever point the capacity is executed, the code consequently sends a callback. As the quantity of capacities develops, so does the number of callbacks — and you end up in a circumstance known as the callback damnation. 

In any case, Node.js offers an exit plan. You can utilize systems that will plan capacities and sort through callbacks. Systems will associate comparable capacities consequently — so you can track down an essential component via search or in an envelope. At that point, there’s no compelling reason to look through callbacks.

 

Final Words

So, these are some of the top benefits of Nodejs in web application development. This is how Nodejs is contributing a lot to the field of web application development. 

I hope now you are totally aware of the whole process of how Nodejs is really important for your web project. If you are looking to hire a node js development company in India then I would suggest that you take a little consultancy too whenever you call. 

Good Luck!

Original Source

#node.js development company in india #node js development company #hire node js developers #hire node.js developers in india #node.js development services #node.js development

Node JS Development Company| Node JS Web Developers-SISGAIN

Top organizations and start-ups hire Node.js developers from SISGAIN for their strategic software development projects in Illinois, USA. On the off chance that you are searching for a first rate innovation to assemble a constant Node.js web application development or a module, Node.js applications are the most appropriate alternative to pick. As Leading Node.js development company, we leverage our profound information on its segments and convey solutions that bring noteworthy business results. For more information email us at hello@sisgain.com

#node.js development services #hire node.js developers #node.js web application development #node.js development company #node js application

sophia tondon

sophia tondon

1621320738

Angular.JS vs Node.JS || Find the best for your project - Valuecoders

Whether MNCs or Startups, many companies use Angular.JS or Node.JS to develop web applications as these are among the best JavaScript frameworks used for web applications.

According to Statista, Node.JS and Angular.JS are the best frameworks used by developers, with 51.4% and 25.1%, respectively.

Both these frameworks have unique features and advantages, which makes them preferred over the other frameworks.

Many enterprises use these frameworks without even understanding their uniqueness and the type of projects they are suited or made, which is why, today, I will compare some of the best features and advantages of these two frameworks.

So, let’s dive into and learn various things about Angular.JS vs Node.JS without any further delay.

Angular.JS

AngularJS is a fundamental framework for robust web apps. It makes you use HTML as your template language and allows you to spread HTML’s syntax to clearly and succinctly express your application’s components.

AngularJS’s dependency injection & data binding eliminate much of the code you would otherwise have to write. And it all happens within the browser, making it a perfect partner with any server technology.

AngularJS is what HTML would have been having it been designed for applications. HTML is a great declarative language for static documents. It does not contain much in creating applications.

Let’s discuss some main features of Angular.JS and its advantages:

Data Binding

Data binding is probably the most impressive and helpful feature of AngularJS. It will save you from writing a considerable amount of repetitive code.

A typical web application can contain up to 80% of its codebase, dedicated to traversing, manipulating, and listening to the DOM. Data binding makes this code escape so you can concentrate more on your application. Think of your Model as the only source of truth for your application. Your model is where you go to read or update anything in your application.

Data binding directives provide a projection of your Model to the application’s view. This projection is perfect and occurs without any effort on your part.

HTML UI

Another great feature of AngularJS is the fact that it uses the HTML language to build UI. The HTML language is a general and declarative language with concise tags that are easy to understand.

This leads to a more systematic and straightforward UI. JavaScript interfaces are usually more challenging to organize and develop. If you’re looking for a solution that’s fast, easy, and simple to use at a moment’s notice, then this could be it.

Model View Controller (MVC)

MVC is a software design pattern for developing web applications. It is made up of:

Directives allow angular to provide additional functionality with the HTML language. Directives can also be used to “decorate” components with behavior and manipulate DOM attributes in interesting ways. The controller does not need to control the DOM directly, as this must be done through directives.

Directives are a separate part of the set of elements that can be used anywhere other than a web application. The directives provide developers with the element-rich HTML they need to strengthen their online presence.

If you are looking to hire a dedicated angular developer, you can hire an angular js development company.

Node.js is a free and open-source server environment that runs on various platforms(Windows, Linux, Unix, Mac, OS X, etc.). Node.js uses JavaScript on the server.

Node.js is preferred because of its rich library of several JavaScript modules that helps in simplifying web development to a greater extent. Many companies hire Node.js developers for making a NodeJS web application development as it possesses many features.

Read More - https://www.valuecoders.com/blog/technology-and-apps/angular-js-vs-node-js-find-the-best-for-your-project/

#hire nodejs developer #node js development services #hire node js developer #hiring node js developers #hire node js developers #hire dedicated angular js developer