Skip to content

Instantly share code, notes, and snippets.

@farshed
Last active November 27, 2022 08:27
Show Gist options
  • Save farshed/548fc8de207896273854a59ff281810b to your computer and use it in GitHub Desktop.
Save farshed/548fc8de207896273854a59ff281810b to your computer and use it in GitHub Desktop.
Minimal localhost file server with TS support
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'
});
@farshed
Copy link
Author

farshed commented Nov 27, 2022

Dependencies

"open": "^8.4.0",
"serve-static": "^1.15.0"

TS support is enabled by default and tsc is expected to be available at runtime. To disable, set compilelock to true.

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