Promisify dgram module
npm install dgram-as-promised




This module provides promisified version of the standard
dgram class. The API is the same as for
standard dgram, except bind, close and send methods which return
Promise
object.
This module requires ES2021 with Node >= 16.
``shell`
npm install dgram-as-promised
_Additionally for Typescript:_
`shell`
npm install -D @types/node
dgram-as-promised can be used similarly to the standard dgram module.
_Example:_
`js
import DgramAsPromised from "dgram-as-promised"
const socket = DgramAsPromised.createSocket("udp4")
const MEMBERSHIP = "224.0.0.1"
const PORT = 41234
const message = Buffer.from("ABCDEFGH")
`
Method bind returns Promise object which resolves to address info whenlistening event is emitted.
`jsSocket is listening on ${address.address}:${address.port}
const address = await socket.bind()
console.log()
socket.setBroadcast(true)
socket.setMulticastTTL(128)
socket.addMembership(MEMBERSHIP)
console.log("Membership is set")
`
Method send returns Promise object which is fulfilled when the message
has been sent.
`jsMessage is sent (${bytes} bytes)
const bytes = await socket.send(message, 0, message.length, PORT, MEMBERSHIP)
console.log()`
Method recv returns Promise object which resolves to the object with msgrinfo
and properties as from message event or resolves to undefined when
the socket is already closed.
It throws an error if a timeout occurs and it was set by setTimeout method.
`jsReceived message: ${packet.msg.toString()}
const packet = await socket.recv()
if (packet) {
console.log()Received ${packet.rinfo.size} bytes
console.log()`
}
Method close returns Promise object which resolves when close event is
emitted or the socket is already closed.
`js`
await socket.close()
console.log("Socket is closed")
`js`
socket = socket.setTimeout(ms)
Set the timeout used by recv method for the idle socket and after thisrecv
timeout, the method will reject a Promise with a timeout error.
After the error, the socket is not closed and calling another recv method
will reset the timeout.
The method returns this object.
_Example:_
`js`
socket.setTimeout(1000)
await socket.recv()
Method iterate and the socket object returns an asynchronous iterator whichrecv
will call method until the socket is closed.
`js`
for await (const packet of socket) {
console.info(packet.msg.toString())
// Close socket if Ctrl-D is in the message
if (packet.msg.indexOf(4) !== -1) {
await socket.close()
}
}
Method destroy cleans internal listeners.
`js``
socket = socket.destroy()
The method returns this object.
Copyright (c) 2016-2024 Piotr Roszatycki