tsx: Avoid address-already-in-use errors when using watch & inspect

Feature request

When using tsx watch --inspect=..., when files change, the node debug server is briefly stopped & restarted.

This makes sense, but if I’ve attached a debugger in Webstorm, I’d ideally like the debugger to stay connected across restarts / as I’m editing and changing files.

Currently if I tell Webstorm debugger to “Reconnect automatically” on disconnect, it seems to grab the port 9229 before the tsx’s restarted node takes it, so I get an error:

  Starting inspector on 0.0.0.0:9229 failed: address already in use

Why?

I’d like to have a really pleasant “the debugger stays connected and it just works across restarts” workflow.

Alternatives

I’d used ts-node-dev in the past, and I swear they had this working, i.e. somehow webstorm could auto reconnect across restarts, without getting “port in use” conflicts.

Maybe I’m just wrong/making this up though, b/c I’m not sure how they would prevent this, without running their own proxy on the port that forwards to the currently-booted node process…

Otherwise, to work around this, I’m just disabling the webstorm auto-reconnect, and I have to remember to keep clicking “connect debugger” after time I change a file.

Additional context

No response

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Comments: 19 (5 by maintainers)

Most upvoted comments

This happened to me. You need to handle SIGTERM and close your server so the port is released e.g.:

process.on('SIGTERM', async () => {
    await server.close();
});

await server.listen()

I’ve been working with the latest releases, and it seems like https://github.com/esbuild-kit/tsx/pull/116 fixed this!

I’m able to see tsx watch pick up reloads while connected with a debugger and everything works great, the IDE auto-reconnects to the restarted Node process/etc.

So going to close this out. Thanks @privatenumber !

@stephenh @dunckr Note that tsx just passes on the CLI flags to Node.js, so it’s actually Node.js that’s handling it.

You might be able to investigate what sockets need to be closed on SIGTERM using https://github.com/mafintosh/why-is-node-running.

Something worth considering is waiting till the previous child process emits exit before starting the next one here: https://github.com/esbuild-kit/tsx/blob/develop/src/watch/index.ts#L66

@RedCrafter07 Please open a separate issue. Sounds like it’s not directly relevant to this issue, and I’m interested in debugging a reproduction.

I’m not familiar with using the debugger in Node.js so it will likely be a while before I can investigate this.

Feel free to open a PR if you want.