读取所有 .md 文件,将它们转换为 html 并发送

我用来fs读取 .md 格式的文件,我想将其转换为 html 文件。


到目前为止,这是我的代码:


fs = require('fs');

fs.readFile(__dirname + '/posts/react-v16.13.0.md', 'utf8', function (err, data) {

  if (err) {

    return console.log(err);

  }

  console.log(data);

});

该文件位于该文件夹中并具有该名称。


此函数将 .md 文件的内容放入控制台。


为了将它转换为 html,我添加了这个:


const showdown = require('showdown');

converter = new showdown.Converter();

...

fs = require('fs');

fs.readFile(__dirname + '/posts/react-v16.13.0.md', 'utf8', function (

  err,

  data

) {

  if (err) {

    return console.log(err);

  }

  text = data;

  html = converter.makeHtml(text);

  console.log(html);

});

它将文件作为 html 放在日志中,这很好。


我的问题是如果文件夹中有多个文件/posts/,如何读取和发送这些文件?


我想使用 POST 方法将它们发送到前端。


是否可以从文件夹中读取所有文件,转换并发送它们?


郎朗坤
浏览 257回答 4
4回答

汪汪一只猫

从问题下方的评论线程看来,您想要执行以下操作的内容:将给定目录中的所有降价文件转换为 HTML将它们全部发送到一个请求中可用于单页应用程序这是满足所有这些要求的方法。每个帖子的 HTML 都被插入到一个template元素中,其内容可以在 SPA 脚本中被克隆和操作。服务器.js// with `.promises`, we can use `async/await`const fs = require("fs").promises;// ...const getHtmlByFilename = async filename => {  const md = await fs.readFile(    path.join(__dirname, "posts", filename),    "utf-8"  );  return converter.makeHtml(md);};app.get("/", async (request, response) => {  const filenames = await fs.readdir(path.join(__dirname, "posts"));  // we can also use Promise.all  // to map over the filenames in parallel  const htmls = await Promise.all(    filenames.map(async filename => {      const html = await getHtmlByFilename(filename);      return { filename, html };    })  );  response.send(    htmlBoilerplate(      htmls        .map(          ({ filename, html }) =>            `<template id="${filename}">${html}</template>`        )        .join("\n"),      "<h1>SPA</h1>",      '<script src="/public/spa.js"></script>'    )  );});公共/spa.js[...document.querySelectorAll("template")].forEach(template => {  const clone = template.content.cloneNode(true);  const filename = template.id;  const details = document.createElement("details");  const summary = document.createElement("summary");  summary.textContent = filename;  details.appendChild(summary);  details.appendChild(clone);  document.querySelector(".markdown-body").appendChild(details);});

手掌心

const {readdir, readFile} = require('fs');const showdown&nbsp; = require('showdown');const axios = require('axios');let fileHtmlList = [];const converter = new showdown.Converter();readdir(`${__dirname}/posts`, 'utf8', (fsDirError, fileNameList) => {&nbsp; &nbsp; if(!fsDirError) {&nbsp; &nbsp; &nbsp; &nbsp; fileNameList.forEach((fileName) => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; readFile(`${__dirname}/posts/${fileName}`, 'utf8', (fsReadError, fileContent) => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(!fsReadError) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fileHtmlList.push({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fileName: `${__dirname}/posts/${fileName}`,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; htmlContent: converter.makeHtml(fileContent)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return console.error(fsReadError);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; return console.error(fsDirError);&nbsp; &nbsp; }});/* I'm guessing this part from your description, if the content needs to be rendered then the code needs change */let sendFrontEnd = async (data) => {&nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; const response = await axios.post(`urlToSend`, data);&nbsp; &nbsp; &nbsp; &nbsp; console.log(response);&nbsp; &nbsp; } catch (error) {&nbsp; &nbsp; &nbsp; &nbsp; console.error(error);&nbsp; &nbsp; }};fileHtmlList.forEach((item) => {&nbsp; &nbsp; sendFrontEnd(item.htmlContent);});

胡子哥哥

我建议使用 readdir 和 readFile 的同步变体const basePath = __dirname + '/posts/';const htmls = [];fs.readdirSync(basePath).forEach(file => {&nbsp; const text = fs.readFileSync(basePath + file, 'utf8');&nbsp; htmls.push({&nbsp; &nbsp; file,&nbsp; &nbsp; html: converter.makeHtml(text)&nbsp; });});// upload htmls with axios/fetch/ ....

宝慕林4294392

试试这个 js 库<!-- Lightweight client-side loader that feature-detects and load polyfills only when necessary --><script src="https://cdn.jsdelivr.net/npm/@webcomponents/webcomponentsjs@2/webcomponents-loader.min.js"></script><!-- Load the element definition --><script type="module" src="https://cdn.jsdelivr.net/gh/zerodevx/zero-md@1/src/zero-md.min.js"></script>&nbsp; &nbsp; <div class="markdown-body">&nbsp; &nbsp; &nbsp; &nbsp; <zero-md src="README.md"> </zero-md>&nbsp; &nbsp; </div>我强烈建议在 html 文件中使用零降价,因为从您的 readme.md 文件自动更新。如果您使用将自述文件转换为 html,则每次更新自述文件(或更多代码)时都必须手动转换。我源代码中的完整 html<!DOCTYPE html><html>&nbsp; <head>&nbsp; &nbsp; <title>API Get link Zing Mp3</title>&nbsp; &nbsp; <meta name="viewport" content="width=device-width, initial-scale=1.0" />&nbsp; &nbsp; <style>&nbsp; &nbsp; &nbsp; .markdown-body {&nbsp; &nbsp; &nbsp; &nbsp; box-sizing: border-box;&nbsp; &nbsp; &nbsp; &nbsp; min-width: 200px;&nbsp; &nbsp; &nbsp; &nbsp; max-width: 980px;&nbsp; &nbsp; &nbsp; &nbsp; margin: 0 auto;&nbsp; &nbsp; &nbsp; &nbsp; padding: 45px;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; @media (max-width: 767px) {&nbsp; &nbsp; &nbsp; &nbsp; .markdown-body {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; padding: 15px;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; </style>&nbsp; &nbsp; <!-- Lightweight client-side loader that feature-detects and load polyfills only when necessary --><script src="https://cdn.jsdelivr.net/npm/@webcomponents/webcomponentsjs@2/webcomponents-loader.min.js"></script><!-- Load the element definition --><script type="module" src="https://cdn.jsdelivr.net/gh/zerodevx/zero-md@1/src/zero-md.min.js"></script><!-- Simply set the `src` attribute to your MD file and win -->&nbsp; </head>&nbsp; <body>&nbsp; &nbsp; <div class="markdown-body">&nbsp; &nbsp; &nbsp; <zero-md src="README.md">&nbsp; &nbsp; &nbsp; </zero-md>&nbsp; &nbsp; </div>&nbsp; &nbsp; </body></html>如果你使用 nodejs,你可以在你的 readme.md 文件中添加一个路由器app.get('/README.md', function (req, res) {&nbsp; &nbsp; res.sendFile(path.join(__dirname, "README.md"));})
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript