#!/usr/bin/env node import { ArgumentParser } from 'argparse'; import chokidar from 'chokidar'; import express, { Request, Response } from 'express'; import marked from 'marked'; import WebSocket from 'ws'; import * as fs from 'fs'; import * as path from 'path'; import template from './template'; const parser = new ArgumentParser({ add_help: true, description: 'Realtime Markdown preview', }); parser.add_argument('file'); parser.add_argument('-p', '--port', { default: 1729, help: 'The port to run on', type: 'int', }); const { file, port } = parser.parse_args(); const filepath = path.resolve(file); const getRenderedHTML = () => { const fileContents = fs.readFileSync(filepath, 'utf-8'); return marked(fileContents); }; const wss = new WebSocket.Server({ port: 40510, }); wss.on('connection', (ws) => { chokidar.watch(filepath).on('change', () => { ws.send(getRenderedHTML(), (err) => { if (err) console.log(err); }); }); }); const app = express(); app.get('/', (_req: Request, res: Response) => { res.send(template(path.basename(file), getRenderedHTML())); }); app.listen(port, () => { console.log(`Listening at http://localhost:${port}`); });