Last active
January 15, 2025 11:05
-
-
Save farshed/548fc8de207896273854a59ff281810b to your computer and use it in GitHub Desktop.
Minimal localhost file server with TS support
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
const http = require('http'); | |
const subproc = require('child_process'); | |
const serveStatic = require('serve-static'); | |
let compilelock = false; | |
const server = http.createServer((req, res) => { | |
if (!compilelock && req.url?.includes('.js')) { | |
compilelock = true; | |
compileTS() | |
.then((elapsed) => { | |
console.log(`[${timestamp()}] Compiled in ${elapsed}s`); | |
}) | |
.catch((err) => { | |
console.error(`[${timestamp()}] Failed to compile. ${err}`); | |
}) | |
.finally(() => { | |
compilelock = false; | |
}); | |
} | |
serveStatic('.')(req, res, () => null); | |
}); | |
const port = 3000; | |
server.listen(port, () => { | |
const url = `http://localhost:${port}`; | |
console.log(`Server listening at ${url}`); | |
require('open')(url); | |
}); | |
function compileTS() { | |
const start = process.hrtime.bigint(); | |
return new Promise((resolve, reject) => { | |
return subproc.exec('tsc --outDir build', (err, _, stderr) => { | |
const error = err || stderr; | |
if (error) { | |
return reject(error); | |
} | |
const ms = Number((process.hrtime.bigint() - start) / BigInt(1e6)); | |
resolve(ms / 1e3); | |
}); | |
}); | |
} | |
const timestamp = () => | |
new Date().toLocaleTimeString('en-US', { | |
hour: '2-digit', | |
minute: '2-digit', | |
second: '2-digit' | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Dependencies
TS support is enabled by default and
tsc
is expected to be available at runtime. To disable, set compilelock totrue
.