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'))

你可能感兴趣的:(2019-04-04 使用 nodejs 批量替换文件夹下内容)