Preview local Markdown files live in a web browser
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.ts 1.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. #!/usr/bin/env node
  2. import { ArgumentParser } from 'argparse';
  3. import chokidar from 'chokidar';
  4. import express, { Request, Response } from 'express';
  5. import marked from 'marked';
  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. add_help: true,
  12. description: 'Realtime Markdown preview',
  13. });
  14. parser.add_argument('file');
  15. parser.add_argument('-p', '--port', {
  16. default: 1729,
  17. help: 'The port to run on',
  18. type: 'int',
  19. });
  20. const { file, port } = parser.parse_args();
  21. const filepath = path.resolve(file);
  22. const getRenderedHTML = () => {
  23. const fileContents = fs.readFileSync(filepath, 'utf-8');
  24. return marked(fileContents);
  25. };
  26. const wss = new WebSocket.Server({
  27. port: 40510,
  28. });
  29. wss.on('connection', (ws) => {
  30. chokidar.watch(filepath).on('change', () => {
  31. ws.send(getRenderedHTML(), (err) => {
  32. if (err) console.log(err);
  33. });
  34. });
  35. });
  36. const app = express();
  37. app.get('/', (_req: Request, res: Response) => {
  38. res.send(template(path.basename(file), getRenderedHTML()));
  39. });
  40. app.listen(port, () => {
  41. console.log(`Listening at http://localhost:${port}`);
  42. });