forked from haraka/Haraka
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathendpoint.js
More file actions
66 lines (59 loc) · 2.01 KB
/
Copy pathendpoint.js
File metadata and controls
66 lines (59 loc) · 2.01 KB
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
'use strict'
// Socket address parser/formatter and server binding helper
const fs = require('node:fs/promises')
const sockaddr = require('sockaddr')
module.exports = function endpoint(addr, defaultPort) {
try {
if ('string' === typeof addr || 'number' === typeof addr) {
addr = sockaddr(addr, { defaultPort })
const match = /^(.*):([0-7]{3})$/.exec(addr.path || '')
if (match) {
addr.path = match[1]
addr.mode = match[2]
}
}
} catch (err) {
// Return the parse exception instead of throwing it
return err
}
return new Endpoint(addr)
}
class Endpoint {
constructor(addr) {
if (addr.path) {
this.path = addr.path
if (addr.mode) this.mode = addr.mode
} else {
// Handle server.address() return as well as parsed host/port
const host = addr.address || addr.host || '::0'
// Normalize '::' to '::0'
this.host = '::' === host ? '::0' : host
this.port = parseInt(addr.port, 10)
}
}
toString() {
if (this.mode) return `${this.path}:${this.mode}`
if (this.path) return this.path
if (this.host.includes(':')) return `[${this.host}]:${this.port}`
return `${this.host}:${this.port}`
}
// Make server listen on this endpoint, w/optional options
async bind(server, opts) {
opts = { ...opts }
const mode = this.mode ? parseInt(this.mode, 8) : false
if (this.path) {
opts.path = this.path
await fs.rm(this.path, { force: true }) // errors are ignored when force is true
} else {
opts.host = this.host
opts.port = this.port
}
return new Promise((resolve, reject) => {
server.listen(opts, async (err) => {
if (err) return reject(err)
if (mode) await fs.chmod(opts.path, mode)
resolve()
})
})
}
}