forked from coapjs/coap-cli
/
index.js
executable file
·71 lines (57 loc) · 1.99 KB
/
index.js
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
#! /usr/bin/env node
var program = require('commander')
, version = require('./package').version
, request = require('coap').request
, URL = require('url')
, through = require('through2')
, method = 'GET' // default
, url
program
.version(version)
.option('-o, --observe', 'Observe the given resource', 'boolean', false)
.option('-n, --no-new-line', 'No new line at the end of the stream', 'boolean', true)
.option('-p, --payload <payload>', 'The payload for POST and PUT requests')
.option('-q, --quiet', 'Do not print status codes of received packets', 'boolean', false)
.option('-c, --non-confirmable', 'non-confirmable', 'boolean', false)
.usage('[command] [options] url')
;['GET', 'PUT', 'POST', 'DELETE'].forEach(function(name) {
program
.command(name.toLowerCase())
.description('performs a ' + name + ' request')
.action(function() { method = name })
})
program.parse(process.argv)
if (!program.args[0]) {
program.outputHelp()
process.exit(-1)
}
url = URL.parse(program.args[0])
url.method = method
url.observe = program.observe
url.confirmable = !program.nonConfirmable
if (url.protocol !== 'coap:' || !url.hostname) {
console.log('Wrong URL. Protocol is not coap or no hostname found.')
process.exit(-1)
}
req = request(url).on('response', function(res) {
// print only status code on empty response
if (!res.payload.length && !program.quiet)
process.stderr.write('\x1b[1m(' + res.code + ')\x1b[0m\n')
res.pipe(through(function addNewLine(chunk, enc, callback) {
if (!program.quiet)
process.stderr.write('\x1b[1m(' + res.code + ')\x1b[0m\t')
if (program.newLine && chunk)
chunk = chunk.toString('utf-8') + '\n'
this.push(chunk)
callback()
})).pipe(process.stdout)
// needed because of some weird issue with
// empty responses and streams
if (!res.payload.length)
process.exit(0)
})
if (method === 'GET' || method === 'DELETE' || program.payload) {
req.end(program.payload)
return
}
process.stdin.pipe(req)