-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjson-rpc-client.js
More file actions
72 lines (60 loc) · 1.71 KB
/
json-rpc-client.js
File metadata and controls
72 lines (60 loc) · 1.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import { spawn } from "child_process";
import { appendFileSync } from "fs";
import * as readline from "readline";
// Get command line arguments
const args = process.argv.slice(2);
if (args.length === 0) {
console.error("Usage: node json-rpc-client.js <subprocess JSON-RPC 2.0>");
process.exit(1);
}
// Spawn the child process
const childProcess = spawn(args[0], args.slice(1), {
stdio: ["pipe", "pipe", "pipe"],
});
// Create readline interface
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
// Handle child process stdout
childProcess.stdout.on("data", (data) => {
process.stdout.write(data);
promptForMessage();
});
childProcess.stderr.on("data", (data) => {
appendFileSync(`json-rpc-client-${childProcess.pid}.debuglog`, data + "\n", {
encoding: "utf-8",
});
childProcess.pid;
});
//Handle child process errors
childProcess.on("error", (err) => {
console.error("Process error:", err.message);
process.exit(1);
});
childProcess.on("close", (code) => {
console.log(`Process exited with code ${code}`);
process.exit(code);
});
// Function to prompt for JSON-RPC message
function promptForMessage() {
rl.question('Enter JSON-RPC 2.0 message (or "quit" to exit): ', (input) => {
if (input.toLowerCase() === "quit") {
childProcess.kill();
rl.close();
process.exit(0);
}
try {
// Validate JSON format
JSON.parse(input);
// Send message to child process
childProcess.stdin.write(input + "\n");
} catch (err) {
console.error("Invalid JSON:", err.message);
promptForMessage();
}
});
}
// Start the interaction
console.log(`JSON-RPC Client started. Process: ${args.join(" ")}`);
promptForMessage();