node.js implements the transformation from markdowm to HTML

Keywords: github

Introduction to the third party package used

var marked = require('marked');
console.log(marked('I am using __markdown__.'));
// Outputs: <p>I am using <strong>markdown</strong>.</p>
  • Browser Sync package
    The function is to automatically start the root directory of the server, listen to the specified files in the server, and automatically refresh the browser when the file content changes;
    For example:
// Reference Browser Sync module
var browserSync = require("browser-sync");

// Start. / app as a server
browserSync({server: "./app"});

// Call reload method to refresh the core.css file under. / app. Note that the file name is passed in, not the path

When running the entry js file on the command line, start the server automatically and listen to port 3000

Important built-in core API s used

Implementation ideas:

  1. Monitor whether markdown file changes
  2. If it changes, read the md file and call the marked function to convert the content to HTML content
  3. Design HTML template, template reservation {{{style}}} and {{{content}}}}}
  4. Read and write CSS file to template, replace {{{style}}}}
  5. Replace the HTML content with {{{content}}}}
  6. Start browser sync server to refresh browser automatically

Specific code

//Mrakdown Automatic file conversion
const fs = require('fs');
const path = require('path');
const util = require('util');
const marked = require('marked');
const browserSync = require("browser-sync");

var template = `<!DOCTYPE html>
<meta charset="utf-8">
    <title>MD turn HTML</title>
  <div class="vs">
//Accept file path to be converted
const target = path.join(__dirname, process.argv[2] || '../');

// Start browser auto refresh server
browserSync({server: path.dirname(target)});

//Monitoring file changes
fs.watchFile(target, (curr, prev) => {
    console.log(`current file's stats: ${curr.size},previous file's stats: ${prev.size}, `);
    // Judge whether the document has changed or not
    if (curr.mtime === prev.mtime) {
        return false;
    // read md File conversion to HTML
    fs.readFile(target, 'utf8',(error, content) => {
        if (error){
            throw error;
        var html = marked(content);
        fs.readFile(path.join(__dirname, './github.css'), (error, css) => {
            html = template.replace('{{{content}}}', html).replace('{{{style}}}', css);
            // Put together HMTL File saved at current md In the file directory
            var filename = target.replace('.md', '.html');
            fs.writeFile(filename, html, 'utf8', () => {


Posted by KEFE on Sat, 02 May 2020 18:05:19 -0700