Skip to content

Handle Node.js Debug Messages and Improve Port Termination #99

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Mar 17, 2025
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,21 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).

## [3.1.3]

### Added
- Added `debug_mode` configuration option to handle Node.js stdout/stderr messages
- Implemented proper `handle_info/2` callback to handle messages from Node.js processes
- Added safeguards to reset_terminal to prevent errors during termination with invalid ports

### Fixed
- Fixed "unexpected message in handle_info/2" errors when Node.js emits debug messages
- Fixed potential crashes during termination when a port becomes invalid

### Contributors
- @francois-codes for the initial implementation
- Revelry team for refinements

## [3.1.2]

### Changed
Expand Down
18 changes: 17 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,22 @@ directory containing your JavaScript modules.
supervisor(NodeJS, [[path: "/node_app_root", pool_size: 4]])
```

### Debug Mode

When working with Node.js applications, you may encounter debug messages or warnings from the Node.js runtime, especially when using inspector or debugging tools. To properly handle these messages:

```elixir
# In your config/dev.exs or other appropriate config file
config :nodejs, debug_mode: true
```

When `debug_mode` is enabled:
- Node.js stdout/stderr messages will be logged at the info level
- Messages like "Debugger listening on..." will not cause errors
- All Node.js processes will log their output through Elixir's Logger

This is particularly useful during development or when debugging Node.js integration issues.

### Calling JavaScript module functions with `NodeJS.call(module, args \\ [])`.

If the module exports a function directly, like this:
Expand Down Expand Up @@ -111,4 +127,4 @@ module.exports = async function echo(x, delay = 1000) {
}
```

https://github.com/revelrylabs/elixir-nodejs/blob/master/test/js/slow-async-echo.js
https://github.com/revelrylabs/elixir-nodejs/blob/master/test/js/slow-async-echo.js
32 changes: 23 additions & 9 deletions lib/nodejs/worker.ex
Original file line number Diff line number Diff line change
Expand Up @@ -124,21 +124,28 @@ defmodule NodeJS.Worker do
end
end

defp env do
Mix.env()
rescue
_ -> :release
# Determines if debug mode is enabled via application configuration
defp debug_mode? do
Application.get_env(:nodejs, :debug_mode, false)
end

def handle_info({_pid, data}, state) do
with :dev <- env(),
{_, {:eol, msg}} <- data do
# Handles any messages from the Node.js process
# When debug_mode is enabled, these messages (like Node.js debug info)
# will be logged at info level
@doc false
def handle_info({_pid, {:data, {_flag, msg}}}, state) do
if debug_mode?() do
Logger.info("NodeJS: #{msg}")
end

{:noreply, state}
end

# Catch-all handler for other messages
def handle_info(_message, state) do
{:noreply, state}
end

defp decode(data) do
data
|> to_string()
Expand All @@ -149,9 +156,16 @@ defmodule NodeJS.Worker do
end
end

# Safely resets the terminal, handling potential errors if
# the port is already closed or invalid
defp reset_terminal(port) do
Port.command(port, "\x1b[0m\x1b[?7h\x1b[?25h\x1b[H\x1b[2J")
Port.command(port, "\x1b[!p\x1b[?47l")
try do
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added try/rescue to fix crashes when ports are closed during termination. Instead of blowing up with ArgumentError, we now just log and move on. This helps during dev reloading or when containers are shutting down - basically anytime processes are killed unpredictably.

Port.command(port, "\x1b[0m\x1b[?7h\x1b[?25h\x1b[H\x1b[2J")
Port.command(port, "\x1b[!p\x1b[?47l")
rescue
_ ->
Logger.debug("NodeJS: Could not reset terminal - port may be closed")
end
end

@doc false
Expand Down
10 changes: 10 additions & 0 deletions test/js/debug_test/debug_logger.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
// This file outputs debugging information to stdout
console.log("Debug message: Module loading");
console.debug("Debug message: Initializing module");

module.exports = function testFunction(input) {
console.log(`Debug message: Function called with input: ${input}`);
console.debug("Debug message: Processing input");

return `Processed: ${input}`;
};
105 changes: 105 additions & 0 deletions test/nodejs_debug_mode_test.exs
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
defmodule NodeJS.DebugModeTest do
use ExUnit.Case
import ExUnit.CaptureLog

describe "debug_mode functionality" do
test "logs Node.js stdout messages when debug_mode is enabled" do
defmodule TestDebugHandler do
use GenServer
require Logger

def start_link do
GenServer.start_link(__MODULE__, nil)
end

def init(_) do
{:ok, nil}
end

def debug_mode? do
Application.get_env(:nodejs, :debug_mode, false)
end

# The implementation from worker.ex
def handle_info({_pid, {:data, {_flag, msg}} = _data}, state) do
if debug_mode?() do
Logger.info("NodeJS: #{msg}")
end

{:noreply, state}
end
end

# Start the test process
{:ok, pid} = TestDebugHandler.start_link()

# Test with debug_mode disabled (default)
log_without_debug =
capture_log(fn ->
# Simulate debugger message from Node.js
send(pid, {self(), {:data, {:eol, "Debugger listening on ws://127.0.0.1:9229/abc123"}}})
# Wait for any potential logging
Process.sleep(50)
end)

# Verify no logging occurred
refute log_without_debug =~ "NodeJS: Debugger listening"

# Enable debug_mode
Application.put_env(:nodejs, :debug_mode, true)

# Test with debug_mode enabled
log_with_debug =
capture_log(fn ->
# Simulate debugger message from Node.js
send(pid, {self(), {:data, {:eol, "Debugger listening on ws://127.0.0.1:9229/abc123"}}})
# Wait for any potential logging
Process.sleep(50)
end)

# Clean up
Application.delete_env(:nodejs, :debug_mode)

# Verify logging occurred
assert log_with_debug =~ "NodeJS: Debugger listening"
end
end

describe "port safety" do
test "reset_terminal handles invalid ports gracefully" do
defmodule TestPortHandler do
use GenServer
require Logger

def start_link do
GenServer.start_link(__MODULE__, nil)
end

def init(_) do
{:ok, nil}
end

# The implementation from worker.ex
def reset_terminal(port) do
try do
Port.command(port, "\x1b[0m\x1b[?7h\x1b[?25h\x1b[H\x1b[2J")
Port.command(port, "\x1b[!p\x1b[?47l")
rescue
_ ->
Logger.debug("NodeJS: Could not reset terminal - port may be closed")
end
end
end

log =
capture_log(fn ->
# Try to reset an invalid port
TestPortHandler.reset_terminal(:invalid_port)
Process.sleep(50)
end)

# Verify proper error handling
assert log =~ "NodeJS: Could not reset terminal"
end
end
end