Return promise for socket stream
npm install promise-socket




This module allows the conversionnet.Socket stream
into its promisified version, which returnsPromise
object fulfilled when the stream's events occurred.
This module requires Node >= 16.
``shell`
npm install promise-socket
`js`
import PromiseSocket, {TimeoutError} from "promise-socket"
`js`
const promiseSocket = new PromiseSocket(socket)
PromiseSocket object requires socket object to work. Newnet.Socketsocket
object is created if argument is missing.
_Example:_
`js
import net from "node:net"
import PromiseSocket from "promise-socket"
const socket = new net.Socket()
const promiseSocket = new PromiseSocket(socket)
`
`js`
const socket = promiseSocket.stream
Original socket object.
_Example:_
`js`
console.log(promiseSocket.stream.localAddress)
`js`
await connect(port, host)
await connect(path)
await connect(options)
Initiate a connection on a given socket. Promise if fulfilled when connectsocket.connect
event is emitted. Check for
arguments.
_Example:_
`js`
await connect(80, "localhost")
// or
await connect({port: 80, host: "localhost"})
`js`
promiseSocket = socket.setTimeout(ms)
Set the timeout for idle socket and after this timeout the socket will be
destroyed with a TimeoutError. It means that socket methods (connect,read, write, etc.) will be rejected.
The method returns this object.
_Example:_
`js`
socket.setTimeout(1000)
await socket.readAll()
`js`
const chunk = await promiseSocket.read(chunkSize)
Check
PromiseReadable.read
for details.
`js`
const content = await promiseSocket.readAll()
Check
PromiseReadable.readAll
for details.
`js`
for await (const chunk of promiseDuplex.iterate(chunkSize)) {
}
Check
PromiseReadable.iterate
for details.
`js`
for await (const chunk of promiseDuplex.iterate(chunkSize)) {
}
Check
[PromiseReadable[Symbol.asyncIterator]](https://www.npmjs.com/package/promise-readable#symbolasynciterator)
for details.
`js`
await promiseSocket.write(chunk)
Check
PromiseWritable.write
for details.
`js`
await promiseSocket.writeAll(content, chunkSize)
Check
PromiseWritable.writeAll
for details.
`js`
await promiseSocket.end()
Check
PromiseWritable.once
for details.
`js`
const result = await promiseSocket.once(event)
Check
PromiseReadable.once
and
PromiseWritable.once
for details.
`js`
promiseSocket = promiseSocket.destroy()
This method calls destroy method on stream and cleans up all own handlers.
The method returns this object.
`js`
try {
socket.setTimeout(5000).connect({port, host})
} catch (e) {
if (e instanceof TimeoutError) {
console.error("Socket timeout")
}
}
This is an error class that is used when the timeout occurred after using
setTimeout method.
PromiseReadable,
PromiseWritable,
PromiseDuplex,
PromisePiping`.
Copyright (c) 2017-2024 Piotr Roszatycki