3

I am evaluating feathers.js for a project. I like its aspirations. So, I decided to try and build a basic content management system just as a learning endeavor. Things have gone pretty smoothly. However, I want to load some static content (articles) into memory when the app starts. I can't figure out how to do that.

I have my articles in the data/articles directory. Each article is markdown named [title].md. I have a block of JavaScript that I tested in a console app that converts the markdown to HTML. That code uses markdown-js to get the HTML into a JSON object. It looks like this:

const fs = require('fs');
const markdownConverter = require('markdown');
let articles = [];

let files = fs.readdirSync('./data/articles');
for (let i=0; i<files.length; i++) {
  let title = files[i].substr((files[i].lastIndexOf('/')+1), (files[i].length-3));
  let markdown = fs.readFileSync(files[i], 'utf8');
  let html = markdownConverter.toHTML(markdown);

  articles[title] = html;
}

I've added a route in Feathers that works like this:

app.use('/articles/:slug', function(req, res) {
  console.log('loading article: ' + req.params.slug);
  let content = '';
  // TODO: How to get access to the articles array.
  // I want to get the HTML using content = articles[req.params.slug];
  res.render('article', { content: content }); 
});

I'm not sure where to put the code that loads the markdown into an array that I can access when a user requests an article. Where does that belong? My guess is in the app.js file that gets generated when you create a Feathers project using the yeoman generator. Yet, I'm not sure what that actually looks like.

4

1 回答 1

3

Since feathers is an Express app, you should be able to use express middleware. I recommend this one that allows you to create HTML templates for you markdown and serve them statically without creating any parsers or for loops.

https://github.com/natesilva/node-docserver

var docserver = require('docserver');
...
app.use(docserver({
  dir: __dirname + '/docs',  // serve Markdown files in the docs directory...
  url: '/'}                  // ...and serve them at the root of the site
));

Or, this middleware that will preParse the Markdown before serving it as HTML in a Jade template.

https://www.npmjs.com/package/markdown-serve

于 2016-03-31T13:14:07.640 回答