gpt4 book ai didi

javascript - Feathers.js - 加载静态内容

转载 作者:搜寻专家 更新时间:2023-11-01 00:40:30 25 4
gpt4 key购买 nike

我正在评估 feathers.js对于一个项目。我喜欢它的愿望。因此,我决定尝试构建一个基本的内容管理系统,作为一种学习努力。事情进行的还算顺利。但是,我想在应用程序启动时将一些静态内容(文章)加载到内存中。我不知道该怎么做。

我的文章在 data/articles 目录中。每篇文章都是 markdown 命名为 [title].md。我有一个 JavaScript block ,我在控制台应用程序中测试了它,该应用程序将 markdown 转换为 HTML。该代码使用 markdown-js将 HTML 转换为 JSON 对象。它看起来像这样:

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;
}

我在 Feathers 中添加了一条路线,其工作方式如下:

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 });
});

我不确定将加载 markdown 的代码放到一个数组中,当用户请求一篇文章时我可以访问该数组。那属于哪里?我的猜测是在您使用 yeoman 生成器创建 Feathers 项目时生成的 app.js 文件中。然而,我不确定它到底是什么样子。

最佳答案

由于 feathers 是一个 Express 应用程序,您应该能够使用 express 中间件。我推荐这个,它允许您为 Markdown 创建 HTML 模板并静态地提供它们,而无需创建任何解析器或 for 循环。

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
));

或者,这个中间件将在 Jade 模板中将 Markdown 作为 HTML 提供之前对其进行预解析。

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

关于javascript - Feathers.js - 加载静态内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36334250/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com