技术实践
Node读写Html
在搞清楚读写html之前,我们需要先知道读写文件的API

在搞清楚读写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}`)
}
})
}
})
}