Skip to content

Instantly share code, notes, and snippets.

@brandonhill
Created October 8, 2022 12:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brandonhill/87c071ceeb3d52d3b8d3e271ec0724c8 to your computer and use it in GitHub Desktop.
Save brandonhill/87c071ceeb3d52d3b8d3e271ec0724c8 to your computer and use it in GitHub Desktop.
Quick local HTTPS server (Node.js)
const { spawnSync } = require('child_process')
const { createReadStream, existsSync, readFileSync } = require('fs')
const { access } = require('fs/promises')
const https = require('https')
const conf = {
default: 'index.html',
log: {
access: false,
error: true },
mime: {
'css': 'text/css',
'html': 'text/html',
'jpe?g': 'image/jpeg',
'js': 'text/javascript',
'png': 'image/png' }, // add as needed
port: 3000,
// src: './public' // optional
}
const contentType = path => {
let s = 'text/plain'
const m = path.match(/\.([^./?]+)(\?|$)/)
if (!m) return s
const [_, ext] = m
for (const [k, v] of Object.entries(conf.mime))
if (ext.match(new RegExp(k))) return v
return s
}
const crt = 'server.crt'
const key = 'server.key'
if (!(existsSync(crt) && existsSync(key)))
spawnSync('openssl', `req -x509 -out ${crt} -keyout ${key} -newkey rsa:2048 -nodes -sha256 -subj /CN=localhost`.split(' '))
https
.createServer(
{ cert: readFileSync(crt), key: readFileSync(key) },
async (req, res) => {
const path = `${conf.src || __dirname}${req.url}${req.url === '/' ? conf.default : ''}`
try {
await access(path)
conf.log.access && console.log(`200 ${req.url}`)
res.writeHead(200, { 'content-type': contentType(path) })
createReadStream(path).pipe(res)
} catch (e) {
conf.log.error && console.error(`404 ${req.url} ${e.message}`)
res.writeHead(404)
res.end()
}
})
.listen(conf.port)
console.log(`Ready. https://localhost${conf.port === 80 ? '' : ':' + conf.port}`)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment