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

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

作者: Armin0202 | 来源:发表于2019-04-04 15:03 被阅读0次
    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 批量替换文件夹下内容

          本文链接:https://www.haomeiwen.com/subject/zkzfiqtx.html