2019-04-04 使用 nodejs 批量替换文件夹下内容

const path = require('path')
const fs = require('fs')
const shelljs = require('shelljs')
const { sftpPath } = require('../src/api/config')

function resolve(fakepath) {
  return path.resolve(__dirname, '..', fakepath)
}

function update(rootpath) {
  fs.readdir(resolve(rootpath), 'utf8', function(err, dirList) {
    if (err) {
      throw err
    }
    dirList.forEach(function(item) {
      let stats = fs.statSync(resolve(`${rootpath}/${item}`))
      if (stats.isDirectory()) {
        // 文件夹
        if (item === 'npm') return undefined
        update(`${rootpath}/${item}`)
      } else {
        // 文件
        if (stats.size > 200 * 1024) return undefined
        fs.readFile(resolve(`${rootpath}/${item}`), 'utf8', function(err, file) {
          if (err) {
            throw err
          }
          // 文件
          let newFile = ''
          if (/\.json$/.test(item)) {
            newFile = file.replace(/(['"]{1})([./]*assets\/images\/)/g, function($0, $1) {
              return `${$1}${sftpPath}/ebank/images/`
            })
          } else if (/\.js$/.test(item)) {
            newFile = file.replace(/(['"]{1})([./]*assets\/images\/)/g, function($0, $1) {
              return `${$1}${sftpPath}/ebank/images/`
            })
          } else if (/\.wxss|\.css/.test(item)) {
            newFile = file.replace(/(url\(['"]?)([./]*assets\/images\/)/g, function($0, $1) {
              return `${$1}${sftpPath}/ebank/images/`
            })
          } else if (/\.wxml/.test(item)) {
            newFile = file.replace(/(['"]{1})([./]*assets\/images\/)/g, function($0, $1) {
              return `${$1}${sftpPath}/ebank/images/`
            })
          }
          if (newFile) {
            fs.writeFile(resolve(`${rootpath}/${item}`), newFile, 'utf8', function(err) {
              if (err) {
                console.log(err)
                throw err
              }
            })
          }
        })
      }
    })
  })
}

update('dist')
shelljs.rm('-rf', resolve('dist/assets/images'))
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容