Skip to content

Instantly share code, notes, and snippets.

@anthumchris
Last active June 23, 2025 04:35
Show Gist options
  • Save anthumchris/79eb906e6271fc719cb5a2b341757e76 to your computer and use it in GitHub Desktop.
Save anthumchris/79eb906e6271fc719cb5a2b341757e76 to your computer and use it in GitHub Desktop.
HTTPS request with NodeJS TLS Socket
#!/usr/bin/env node
import tls from 'node:tls'
const host = 'one.one.one.one' // Cloudflare DNS
const port = 443
const timeout = 5_000
const path = '/dns/'
const request = trim(`
HEAD ${path} HTTP/1.1
Host: ${host}
Connection: close
`) + '\n\n'
let reads = 0
console.log(`connecting to https://${host}:${port}...`)
const socket = getSocket()
.on('ready', () => {
socket.write(request, () => {
console.log(`—— HTTPS Request ——\n${request}`)
})
})
.on('data', data => {
if (!reads++) {
console.log(`—— HTTPS Response ——`)
}
console.log(data.toString())
})
.on('end', () => console.log('——'))
/* Returns <TLSSocket> with error handling
*
* <tls.TLSSocket> https://nodejs.org/api/tls.html#class-tlstlssocket
* ∟ <net.Socket> https://nodejs.org/api/net.html#class-netsocket
* ∟ <stream.Duplex> https://nodejs.org/api/stream.html#class-streamduplex
*/
function getSocket() {
const socket = tls.connect({ host, port })
.setTimeout(timeout)
.on('error', err => {
socket.once('close', () => {
console.error(err)
throw err
})
})
.on('timeout', () => {
const error = socket.connecting
? Error('connection timeout')
: Error('inactivity timeout')
socket.destroy(error)
})
.on('close', isError => {
console.log('socket closed:', { isError })
})
return socket
}
// trims whitespace from multiline JS template strings
function trim(str) {
return str
.replace(/(^\s*|\s*$)/g, '') // start/end lines
.replace(/\s*\n\s*/g, '\n') // leading/trailing whitespace
}
@anthumchris
Copy link
Author

anthumchris commented Jun 20, 2025

NodeJS test

$ node -v

v22.6.0

$ node httpsSocketRequest.js 

——  HTTPS Request  ——
HEAD /dns/ HTTP/1.1
Host: one.one.one.one
Connection: close


——  HTTPS Response  ——
HTTP/1.1 200 OK
Date: Fri, 20 Jun 2025 00:00:00 GMT
Content-Type: text/html; charset=utf-8
Connection: close
Access-Control-Allow-Origin: *
Cache-Control: public, max-age=0, must-revalidate
ETag: "e3b0b55949321bee09e380eb849f90fd"
Vary: Accept-Encoding
referrer-policy: strict-origin-when-cross-origin
x-content-type-options: nosniff
x-frame-options: DENY
Server: cloudflare
alt-svc: h3=":443"; ma=86400


——
socket closed: { isError: false }

Bun test

$ bun -v

1.2.16

$ bun httpsSocketRequest.js 

——  HTTPS Request  ——
HEAD /dns/ HTTP/1.1
Host: one.one.one.one
Connection: close


——  HTTPS Response  ——
HTTP/1.1 200 OK
Date: Fri, 20 Jun 2025 00:00:00 GMT
Content-Type: text/html; charset=utf-8
Connection: closed
...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment