一键替换页面内容

背景:市场的老师提出来修改官网文案,已经把要修改的文案都标记出来了。(excel黄色标记为 旧的,橙色为新的数据),因为不想一句一句替换,所以就想用代码一键替换。

思路:首先把新旧数据提取出来,然后转换成json数据,然后在替换页面中的文字。
技术:node(内置fs模块用于读写文件、node-xlsx模块用于生成json数据、lodash模块用于处理数据)
下面有源码分享~

一.生成json代码

1.npm init 新建node工程
2.然后执行npm install node-xlsx lodash安装依赖
3.新建index.json文件,用来存放生成的json数据
4.新建createjson.js文件,代码如下:(old为老数据,new为新数据)

//excel生成json数据
const xlsx = require('node-xlsx');

let _ = require('lodash');
let fs = require('fs')

let excelFile = './index.xlsx'
let list = xlsx.parse(excelFile)
let data = list[0].data;
let arr = []
_.forEach(data.slice(1), (d) => {
    let obj = {
        "old":d[0],
        "new":d[1]
    }
    arr.push(obj)
});
console.log("arr",arr)
fs.writeFile('index.json',JSON.stringify(arr),(err)=>{
    if(err){
        console.log("write error")
    }else{
        console.log("write success")
    }
})

然后执行 node createjson.js ,可以发现已经把生成的json数据写入index.json文件里了。

二.替换html页面内容

//替换页面元素
let fs = require('fs')
fs.readFile('./index.json','utf-8',(err,data)=>{
    if(err){
        console.log("读取错误")
        return
    }
    console.log("")
    data = JSON.parse(data);
    readFun(data,'./index.html')
})

//读取html页面内容,然后替换旧的内容
function readFun(dataArray,oldpath){
    fs.readFile(oldpath,'utf-8',(err,data)=>{
        if(err){
            console.log("读取错误")
            return
        }
        for (let index = 0; index < dataArray.length; index++) {
            data = data.replace(dataArray[index]["old"], dataArray[index]["new"]);
          }
        // let data1 = data.toString()
        writeFun(data)
    })
}

//把新的额数据写入页面
function writeFun(data){
    fs.writeFile('./index.html',data,(err)=>{
        if(err){
            console.log("write error")
        }else{
            console.log("write success")
        }
    })
}

执行node index.js,可以发现html的内容已经被替换了。大致思路是这样的,写了一个简单的demo,感兴趣的同学可以评论交流~
demo地址:提取码: wgbf

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

郭二不语

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值