index.js

 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    if (buffer.length < 4 + length) {
21        return;
22    }
23
24    const bytes = buffer.subarray(4, 4 + length);
25    buffer = buffer.subarray(4 + length);
26
27    try {
28        const message = JSON.parse(bytes);
29        handleMessage(message);
30    } catch (_) {
31        sendResponse(makeError("Request JSON parse error"));
32        return;
33    }
34}
35
36// format
37// clear_cache
38// shutdown
39// error
40
41function handleMessage(message) {
42    console.log(message);
43    sendResponse({ method: "hi", result: null });
44}
45
46function makeError(message) {
47    return { method: "error", message };
48}
49
50function sendResponse(response) {
51    let message = Buffer.from(JSON.stringify(response));
52    let length = Buffer.alloc(4);
53    length.writeUInt32LE(message.length);
54    process.stdout.write(length);
55    process.stdout.write(message);
56}