Last active
June 23, 2025 04:35
-
-
Save anthumchris/79eb906e6271fc719cb5a2b341757e76 to your computer and use it in GitHub Desktop.
HTTPS request with NodeJS TLS Socket
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
NodeJS test
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 ...