Browse Source

add test etc

ameba23 2 years ago
parent
commit
6b874fddef
4 changed files with 47 additions and 4 deletions
  1. 19
    0
      README.md
  2. 5
    3
      index.js
  3. 6
    1
      package.json
  4. 17
    0
      test/index.test.js

+ 19
- 0
README.md View File

@@ -0,0 +1,19 @@
1
+
2
+## API
3
+
4
+`const bc = require('try-udp-broadcast')`
5
+
6
+### `const destroy = bc.broadcast(msg, [opts])`
7
+
8
+Broadcast a message regularly.
9
+- `destroy` is a function which you can call with no arguments to stop broadcasting.
10
+- `opts` may include:
11
+  - `opts.interval` interval between packets in ms, default 1000
12
+  - `opts.port` port to broadcast on.
13
+
14
+### `bc.receive(callback [opts])`
15
+
16
+Listen for messages
17
+- `callback` is called whenever a ***unique*** message is found.  That is, whenever the message or address changes. The message is passed in the callback.
18
+- `opts` may include:
19
+  - `opts.port` port to listen to

+ 5
- 3
index.js View File

@@ -3,7 +3,7 @@ const createStream = require('broadcast-stream')
3 3
 const PORT = 8999
4 4
 const INTERVAL = 1000
5 5
 
6
-module.exports = { broadcast, recieve }
6
+module.exports = { broadcast, receive }
7 7
 
8 8
 function broadcast (msg, opts = {}) {
9 9
   const port = opts.port || PORT
@@ -14,12 +14,14 @@ function broadcast (msg, opts = {}) {
14 14
   msg = msg || Buffer.from('cobox replicator over here', 'utf8')
15 15
   const interval = opts.inverval || INTERVAL
16 16
 
17
-  setInterval(() => {
17
+  const destroy = setInterval(() => {
18 18
     stream.write(msg)
19 19
   }, interval)
20
+
21
+  return () => { clearInterval(destroy) && stream.destroy() }
20 22
 }
21 23
 
22
-function recieve (callback, opts = {}) {
24
+function receive (callback, opts = {}) {
23 25
   const port = opts.port || PORT
24 26
   const stream = createStream(port)
25 27
   const foundMsgs = []

+ 6
- 1
package.json View File

@@ -4,11 +4,16 @@
4 4
   "description": "",
5 5
   "main": "index.js",
6 6
   "scripts": {
7
-    "test": "echo \"Error: no test specified\" && exit 1"
7
+    "test": "tape test/**/*.test.js | tap-spec"
8 8
   },
9 9
   "author": "",
10 10
   "license": "ISC",
11 11
   "dependencies": {
12 12
     "broadcast-stream": "^0.2.2"
13
+  },
14
+  "devDependencies": {
15
+    "tap-spec": "^5.0.0",
16
+    "tape": "^4.11.0",
17
+    "tape-plus": "^1.0.0"
13 18
   }
14 19
 }

+ 17
- 0
test/index.test.js View File

@@ -0,0 +1,17 @@
1
+const { describe } = require('tape-plus')
2
+const { broadcast, receive } = require('..')
3
+
4
+describe('basic', (context) => {
5
+  context('broadcast and receive', (assert, next) => {
6
+    const destroy = broadcast(null, { interval: 1000 })
7
+
8
+
9
+    console.log(destroy)
10
+    setTimeout(() => {
11
+      destroy()
12
+    }, 2000)
13
+    // receive((msg) => {
14
+    //   console.log(msg)
15
+    // })
16
+  })
17
+})