技术实践

Node读写Html

在搞清楚读写html之前,我们需要先知道读写文件的API

羊先生的头像
羊先生2021.08.25 · 1 分钟阅读 · 43 阅读
Node读写Html封面
文章正文还需 1 分钟

在搞清楚读写html之前,我们需要先知道读写文件的API

使用 Node.js 读取文件

js 复制代码
onst fs = require('fs')

fs.readFile('/Users/joe/test.txt', 'utf8' , (err, data) => {
  if (err) {
    console.error(err)
    return
  }
  console.log(data)
})

写入文件writeFile

js 复制代码
const fs = require('fs')

const content = '一些内容'

fs.writeFile('/Users/joe/test.txt', content, err => {
  if (err) {
    console.error(err)
    return
  }
  //文件写入成功。
})

读写Html

js 复制代码
const { copyFile } = require('../../utils/index')
const path = require('path')
const chalk = require('chalk')
const ora = require('ora')
const fs = require('fs')
const cheerio = require('cheerio')

const log = (str) => {
    console.log(chalk.blue(str))
}

const getHtml = ({ targetDir, answers }) => {
    const _path = path.join(targetDir, 'index.html')
    fs.readFile(_path, function (err, data) {
        if (err) {
            return
        }
        else {
            let person = data.toString()
            let $ = cheerio.load(person)
            $('meta[name="author"]').attr('content', answers.author)
            $('meta[name="description"]').attr('description', answers.description)
            let str = $.html()
            fs.writeFile(_path, str, function (err) {
                if (err) {
                    return
                }
                else {
                    log(`🎉  模板创建完成...`)
                    console.log()
                    log(` $ cd ${targetDir}`)
                }
            })
        }
    })
}

【cheerio教程】