Read lines off `socket` as they come.
(socket: net.Socket)
| 151 | |
| 152 | /** Read lines off `socket` as they come. */ |
| 153 | function lineReader(socket: net.Socket): () => Promise<string> { |
| 154 | let buffer = ''; |
| 155 | const waiting: Array<(line: string) => void> = []; |
| 156 | const lines: string[] = []; |
| 157 | socket.setEncoding('utf8'); |
| 158 | socket.on('data', (chunk: string) => { |
| 159 | buffer += chunk; |
| 160 | let newline: number; |
| 161 | while ((newline = buffer.indexOf('\n')) !== -1) { |
| 162 | const line = buffer.slice(0, newline); |
| 163 | buffer = buffer.slice(newline + 1); |
| 164 | const next = waiting.shift(); |
| 165 | if (next) next(line); else lines.push(line); |
| 166 | } |
| 167 | }); |
| 168 | return () => new Promise((resolve, reject) => { |
| 169 | const line = lines.shift(); |
| 170 | if (line !== undefined) return resolve(line); |
| 171 | const timer = setTimeout(() => reject(new Error('no line within 5s')), 5_000); |
| 172 | waiting.push((l) => { clearTimeout(timer); resolve(l); }); |
| 173 | }); |
| 174 | } |
| 175 | |
| 176 | describe('the daemon answers a challenge in its handshake (#3284)', () => { |
| 177 | /** A real Daemon's connection handling, on a socket of its own. Opens no index. */ |