Examples
HTTP Server
This example demonstrates how to create a simple HTTP server using the @jsh/http
module.
The server listens on a specified address and port (127.0.0.1:56802
)
and provides a RESTful API endpoint (/hello/:name
).
When a client sends a GET request to this endpoint with a name parameter,
the server responds with a JSON object containing a greeting message and the provided name.
This example is ideal for learning how to build lightweight HTTP servers with dynamic routing and JSON responses in JavaScript.
Key Features:
- Daemonization: The script checks if it is running as a daemon using
process.ppid()
. If not, it daemonizes itself usingprocess.daemonize()
to run in the background. - Routing: The server uses a route (
/hello/:name
) to extract thename
parameter from the URL. - JSON Response: The server responds with a JSON object containing the
name
and a greeting message.
|
|
Usage:
- Run the script to start the server.
- Use a tool like
curl
to send a GET request to the server:
curl -o - http://127.0.0.1:56802/hello/Karl
The server will respond with:
{"message":"greetings","name":"Karl"}
Unix Domain Socket
The Unix Domain Socket example demonstrates how to create an HTTP server that communicates using a Unix domain socket instead of a TCP/IP network socket. This approach is useful for inter-process communication (IPC) on the same machine.
Workflow:
- Unix Domain Socket Communication:
- Uses a file-based socket (/tmp/service.sock) for local communication.
- Efficient IPC:
- Ideal for scenarios where processes on the same machine need to communicate without network overhead.
- Compatibility with Tools:
- Supports tools like curl for testing and interacting with the server.
|
|
Use curl to send a request to the server via the Unix domain socket:
curl -o - --unix-socket /tmp/service.sock http://localhost/hello/Karl
Static Content
|
|
Redirect
|
|
RESTful API
|
|
- GET
curl -o - http://127.0.0.1:56802/movies
[
{ "id": 59793, "studio": [ "Paramount" ], "title": "Indiana Jones" },
{ "id": 64821, "studio": [ "Lucasfilm" ], "title": "Indiana Jones" }
]
- POST
curl -o - -X POST http://127.0.0.1:56802/movies \
-H "Content-Type: application/json" \
-d '{"title":"new movie", "id":12345, "studio":["Unknown"]}'
- DELETE
curl -v -o - -X DELETE http://127.0.0.1:56802/movies/12345
< HTTP/1.1 204 No Content
< Content-Type: text/plain; charset=utf-8
< Date: Thu, 08 May 2025 20:39:34 GMT
<
HTTP Client
This example demonstrates how to create an HTTP client using the @jsh/http
module.
The client sends a GET request to a specified URL and processes the server’s response.
It showcases how to handle HTTP requests and parse JSON responses in JavaScript.
This example is ideal for learning how to build HTTP clients in JavaScript, handle responses, and parse JSON data.
Key Features:
- Request Handling: The client sends an HTTP GET request to the server.
- Response Parsing: The response is parsed to extract details such as status, headers, and body content.
- Error Handling: The example includes a
try-catch
block to handle potential errors during the request.
|
|
Usage:
- Ensure the HTTP server is running (refer to the HTTP Server example).
- Run the script to send a GET request to the server.
Unix Domain Socket
Use {unix: "/path/to/unix_domain_socket/file"}
option to connect server using the unix domain socket.
|
|
MQTT Subscriber
The MQTT Subscriber example demonstrates how to create a background application that connects to an MQTT broker, subscribes to a specific topic, and processes incoming messages.
Using the @jsh/process
and @jsh/mqtt
modules, the script runs as a daemon, ensuring it operates in the background.
It handles events such as connection establishment, message reception, and disconnection, showcasing how to build a robust and efficient MQTT client in JavaScript.
This example is ideal for scenarios requiring real-time message processing and lightweight background operations.
- Create an application as
mqtt-sub.js
.
|
|
- Run
mqtt-sub.js
from JSH.
jsh / > mqtt-sub
jsh / > ps
┌──────┬──────┬──────┬───────────────────┬────────┐
│ PID │ PPID │ USER │ NAME │ UPTIME │
├──────┼──────┼──────┼───────────────────┼────────┤
│ 1025 │ - │ sys │ jsh │ 4m8s │
│ 1037 │ 1 │ sys │ /sbin/mqtt-sub.js │ 1s │
│ 1038 │ 1025 │ sys │ ps │ 0s │
└──────┴──────┴──────┴───────────────────┴────────┘
- Send messages using mosquitto_pub or any other MQTT client.
mosquitto_pub -h 127.0.0.1 -p 5653 -t test/topic -m 'hello?'
The mqtt-sub.js
application received the published message via the subscription.
2025/05/02 09:56:18.381 INFO /sbin/mqtt-sub.js mqtt-sub start...
2025/05/02 09:56:18.382 INFO /sbin/mqtt-sub.js connected.
2025/05/02 09:56:18.383 INFO /sbin/mqtt-sub.js subscribe to test/topic
2025/05/02 09:56:26.149 INFO /sbin/mqtt-sub.js recv topic: test/topic QoS: 0 payload: hello?
- You can
stop the background process
mqtt-sub.js
withkill <pid>
command.
jsh / > kill 1037
jsh / > ps
┌──────┬──────┬──────┬──────┬────────┐
│ PID │ PPID │ USER │ NAME │ UPTIME │
├──────┼──────┼──────┼──────┼────────┤
│ 1025 │ - │ sys │ jsh │ 16m50s │
│ 1041 │ 1025 │ sys │ ps │ 0s │
└──────┴──────┴──────┴──────┴────────┘
Machbase Client
This example demonstrates how to connect to another Machbase instance via port 5656 and execute a query.
Set lowerCaseColumns: true
at line 8 to ensure that the query results use lower-cased property names in the record object, as demonstrated at line 21.
sourceSource
supports two formats for historical reasons: the first uses a semi-colon delimiter, while the second uses a space delimiter. Both are equivalent.
- Classic Format:
SERVER=${host};PORT_NO=${port};UID=${user};PWD=${pass}
- Name=Value Format:
host=<ip> port=<port> user=<username> password=<pass>
|
|
Machbase Append
|
|
SQLite
This example demonstrates how to use the @jsh/db
module to interact with an in-memory SQLite database.
It covers creating a table, inserting data, and querying the database.
This example is ideal for learning how to perform basic database operations in JavaScript using SQLite.
|
|
When the script is run, it outputs the inserted record:
1 Fedel-Gaylord 12
System Monitoring
Data Collector
The System Monitoring example demonstrates how to create a lightweight system monitoring tool using the @jsh/process
and @jsh/psutil
modules.
This script runs as a background daemon and periodically collects key system metrics, such as CPU usage, memory utilization, and load averages over the past 1, 5, and 15 minutes.
The monitoring task is scheduled to execute every 15 seconds using a cron-like syntax. The collected data is formatted and printed with timestamps, providing a clear snapshot of the system’s performance at regular intervals. This example showcases how to leverage JavaScript for efficient process management and real-time system monitoring.
Save the example code as sysmon.js
and execute it through the JSH
terminal.
It will store system load averages, CPU usage, and memory utilization percentages into the database table named “EXAMPLE”.
jsh / > sysmon
jsh / > ps
┌──────┬──────┬──────┬─────────────────┬──────────┐
│ PID │ PPID │ USER │ NAME │ UPTIME │
├──────┼──────┼──────┼─────────────────┼──────────┤
│ 1040 │ 1 │ sys │ /sysmon.js │ 2h37m43s │
│ 1042 │ 1025 │ sys │ ps │ 0s │
└──────┴──────┴──────┴─────────────────┴──────────┘
- sysmon.js
|
|
Chart TQL
Since the system usage data is stored in the database, querying and visualizing it becomes straightforward.
|
|

Chart TQL with SCRIPT
|
|

Charts in HTML
Save the following HTML code as sysmon.html
and open it in a web browser to visualize the system monitoring data.
- sysmon.html
|
|

OPCUA Client
The OPCUA Client example demonstrates how to create a data collector that connects to an OPC UA server, retrieves system metrics, and stores them in a database for further analysis and visualization.
Workflow:
- OPC UA Integration:
- Connects to an OPC UA server using the
@jsh/opcua
module to read data. - The script connects to an OPC UA server at
opc.tcp://localhost:4840
. - It reads specific nodes (e.g.,
cpu_percent
,mem_percent
,load1
, etc.) to retrieve system metrics.
- Connects to an OPC UA server using the
- Scheduled Data Collection:
- Uses a cron-like schedule to periodically fetch data from the OPC UA server.
- The script schedules a task to run every 10 seconds using
process.schedule
. - At each interval, it reads the values of the specified nodes and stores them in the database.
- Database Storage:
- Stores the collected data in a database table (
EXAMPLE
) for persistence and analysis. - The collected data is inserted into the
EXAMPLE
table with columns forname
,time
, andvalue
.
- Stores the collected data in a database table (
- Data Visualization:
- The collected data can be visualized using the chart examples provided in the System Monitoring example.
- The stored data can be visualized using the chart examples from the System Monitoring example. For instance, you can use the provided TQL or HTML chart examples to display metrics like CPU usage, memory utilization, and load averages.
Data Collector
Save the script as opcua-client.js and run it in the background using the JSH terminal:
jsh / > opcua-client
jsh / > ps
┌──────┬──────┬──────┬──────────────────┬────────┐
│ PID │ PPID │ USER │ NAME │ UPTIME │
├──────┼──────┼──────┼──────────────────┼────────┤
│ 1044 │ 1 │ sys │ /opcua-client.js │ 13s │
│ 1045 │ 1025 │ sys │ ps │ 0s │
└──────┴──────┴──────┴──────────────────┴────────┘
- opcua-client.js
|
|