1const { Buffer } = require('buffer');
2
3let buffer = Buffer.alloc(0);
4process.stdin.resume();
5process.stdin.on('data', (data) => {
6 buffer = Buffer.concat([buffer, data]);
7 handleData();
8});
9process.stdin.on('end', () => {
10 handleData();
11});
12
13function handleData() {
14 if (buffer.length < 4) {
15 return;
16 }
17
18 const length = buffer.readUInt32LE(0);
19 console.log(length);
20 console.log(buffer.toString());
21 if (buffer.length < 4 + length) {
22 return;
23 }
24
25 const bytes = buffer.subarray(4, 4 + length);
26 buffer = buffer.subarray(4 + length);
27
28 try {
29 const message = JSON.parse(bytes);
30 handleMessage(message);
31 } catch (_) {
32 sendResponse(makeError("Request JSON parse error"));
33 return;
34 }
35}
36
37// format
38// clear_cache
39// shutdown
40// error
41
42function handleMessage(message) {
43 console.log(message);
44 sendResponse({ method: "hi", result: null });
45}
46
47function makeError(message) {
48 return { method: "error", message };
49}
50
51function sendResponse(response) {
52 let message = Buffer.from(JSON.stringify(response));
53 let length = Buffer.alloc(4);
54 length.writeUInt32LE(message.length);
55 process.stdout.write(length);
56 process.stdout.write(message);
57}