| 19 | } |
| 20 | |
| 21 | function send(path, method = 'GET', body) { |
| 22 | return new Promise((resolve, reject) => { |
| 23 | const data = body ? JSON.stringify(body) : null; |
| 24 | const req = http.request({ |
| 25 | hostname: 'localhost', |
| 26 | port: PORT, |
| 27 | path, |
| 28 | method, |
| 29 | headers: data ? { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(data) } : {} |
| 30 | }, (res) => { |
| 31 | let out = ''; |
| 32 | res.on('data', chunk => out += chunk); |
| 33 | res.on('end', () => { |
| 34 | if (res.statusCode >= 400) { |
| 35 | reject(out); |
| 36 | } else { |
| 37 | resolve(out); |
| 38 | } |
| 39 | }); |
| 40 | }); |
| 41 | req.on('error', (e) => { |
| 42 | if (e.code === 'ECONNREFUSED') { |
| 43 | reject('Daemon is not running. Please start it with "br start".'); |
| 44 | } else { |
| 45 | console.log('Unknown error, try start the daemon with "br start":'); |
| 46 | console.error(e); |
| 47 | } |
| 48 | }); |
| 49 | if (data) req.write(data); |
| 50 | req.end(); |
| 51 | }); |
| 52 | } |
| 53 | |
| 54 | program |
| 55 | .command('start') |