Saturday, 15 April 2017

How to render Markdown using Node.js Express, Mongo and Markdown-it?

I am entirely new to the world of markdown and trying to get my head around it.

I hacked together a basic node Express app. It is reading some sample markdown text from a mongodb database, then using markdown-it middleware to process the markdown.

var express = require('express');
var MongoClient = require('mongodb').MongoClient;
var fs = require('fs');
var path = require('path');

var md = require('markdown-it')({
  html: true,
  linkify: true,
  typographer: true
});

var app = express();

app.set('views', path.resolve(__dirname, 'views'));
app.set('view engine','ejs');

// Connect to the db
MongoClient.connect("mongodb://localhost:27017/mdtest1", function(err, db) {
  if(!err) {
    console.log("We are connected");
  }
});

app.use('/2',function(req,res){
    MongoClient.connect("mongodb://localhost:27017/mdtest1", function(err, db) {
        var collection2 = db.collection('mdcol');
        var ObjectId = require('mongodb').ObjectId;
        var o_id = new ObjectId('58f273ae624c4d435c632fa0');
        collection2.findOne({}, function(err, document) {
            //console.log(document.body);
            console.log('--------------------------------------------------')
            var result = md.render(document.body);
            console.log(result);
            res.render('md', {
                'main': result
            });
        });
    });
});

app.listen(3000);

My question is: how do I render this in a template? I am using ejs templating where the following variable is displayed:

<%= main %>

Bu this displays HTML as text on the page.

What am I doing wrong? Thanks!



via Aivoric

No comments:

Post a Comment