Preview local Markdown files live in a web browser
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

index.ts 1.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. #!/usr/bin/env node
  2. import { ArgumentParser } from 'argparse';
  3. import chokidar from 'chokidar';
  4. import express, { Request, Response } from 'express';
  5. import Remarkable from 'remarkable';
  6. import WebSocket from 'ws';
  7. import * as fs from 'fs';
  8. import * as path from 'path';
  9. import template from './template';
  10. const parser = new ArgumentParser({
  11. version: '0.1.0',
  12. addHelp: true,
  13. description: 'Realtime Markdown preview',
  14. });
  15. parser.addArgument('file');
  16. parser.addArgument(
  17. ['-p', '--port'],
  18. {
  19. defaultValue: 1729,
  20. help: 'The port to run on',
  21. type: 'int' }
  22. );
  23. const { file, port } = parser.parseArgs();
  24. const filepath = path.resolve(file);
  25. const getRenderedHTML = () => {
  26. const md = new Remarkable();
  27. const fileContents = fs.readFileSync(filepath, 'utf-8');
  28. return md.render(fileContents);
  29. };
  30. const wss = new WebSocket.Server({
  31. port: 40510,
  32. });
  33. wss.on('connection', (ws) => {
  34. chokidar.watch(filepath).on('change', () => {
  35. ws.send(getRenderedHTML(), (err) => {
  36. if (err) console.log(err);
  37. });
  38. });
  39. });
  40. const app = express();
  41. app.get('/', (_req: Request, res: Response) => {
  42. res.send(template(path.basename(file), getRenderedHTML()));
  43. });
  44. app.listen(port, () => {
  45. console.log(`Listening at http://localhost:${port}`);
  46. });