编程语言
首页 > 编程语言> > 利用node.js进行文件转换 将markdown文件转为html文件

利用node.js进行文件转换 将markdown文件转为html文件

作者:互联网

不限于mad文件到html文件的转换,可对照着  做 txt html 等等的相互转换.

 思路如下:

  1. 读取 Markdown 文件的内容

    fs.readFile()

  2. 把 Markdown 内容转换为 HTML 标签

    (1)把读取到的内容按照换行符(\n)进行 split 分割

    (2)进行字符串的 replace 替换操作

  3. 写入 HTML 文件

    fs.writeFile()

md内容如下

# Markdown 文件的一级标题

startsWith() 方法用来判断当前字符串是否以另外一个给定的子字符串开头,并根据判断结果返回 true 或 false。
正文段落部分正文段落部分正文段落部分

## Markdown 文件的二级标题

正文段落部分正文段落部分正文段落部分
正文段落部分正文段落部分正文段落部分

### Markdown 文件的三级标题

正文段落部分正文段落部分正文段落部分
正文段落部分正文段落部分正文段落部分
const fs = require('fs')
const path = require('path')
fs.readFile(path.join(__dirname, './template.md'),'utf8',(err,data)=>{
    const arr = data.split('\n') //  
    console.log(arr)
 
    const newArr = []
    arr.forEach(item => {
      if (item.startsWith('# ')) { // 1 级标题(h1)
        newArr.push(`<h1>${item.replace('# ', '')}</h1>`)
      } else if (item.startsWith('## ')) { // 2 级标题(h2)
        newArr.push(`<h2>${item.replace('## ', '')}</h2>`)
      } else if (item.startsWith('### ')) { // 3 级标题(h3)
        newArr.push(`<h3>${item.replace('### ', '')}</h3>`)
      } else { // 普通的段落(p 标签)
        newArr.push(`<p>${item}</p>`)
      }
    })
    // console.log(newArr)

    fs.writeFile(path.join(__dirname, 'README1.html'), newArr.join(''), (err) => {
      if (err) {
        console.log('写入文件失败:' + err.message)
        return
      }
      console.log('转换成功!')
    })
        

})

标签:node,文件,markdown,段落,newArr,正文,item,fs
来源: https://blog.csdn.net/laoli360/article/details/120248056