123456789101112131415161718192021222324252627282930313233343536373839404142 |
- const fs = require('fs')
- module.exports = {
- setData(filePath, updateData = [],savePath='') {
- let fileData = this.read(filePath)
- for (let i in updateData) {
- fileData = this.replaceFile(fileData, i, updateData[i])
- }
- this.save(savePath?savePath:filePath, fileData)
- },
- read(filePath) {
- let file = fs.readFileSync(filePath, {
- encoding: 'utf-8'
- })
- return file
- },
- replaceFile(fileData, path, value) {
- const arr = path.split('.')
- const len = arr.length
- const lastItem = arr[len - 1]
- let i = 0
- let fileArr = fileData.split(/\n/)
- for (let index = 0; index < fileArr.length; index++) {
- const item = fileArr[index]
- if (new RegExp(`"${arr[i]}"`).test(item)) ++i;
- if (i === len) {
- const hasComma = /,/.test(item)
- fileArr[index] = item.replace(new RegExp(`"${lastItem}"[\\s\\S]*:[\\s\\S]*`),
- `"${lastItem}": ${value}${hasComma ? ',' : ''}`)
- break;
- }
- }
- return fileArr.join('\n')
- },
- save(filePath, fileData) {
- fs.writeFileSync(filePath, fileData, {
- "flag": "w"
- })
- }
- }
|