import fs from "fs" ; import path from "path" ; import { TaskConfig } from "./TaskConfig" ; import { TaskInterface } from "./TaskInterface" ; import { RandomUtil } from "../utils/RandomUtil" ; import { toBase64 } from "js-base64" ; enum TextType { TXT , JSON } type TextObject = { /**
     * 图片类型
     */ type : TextType ; /**
     * 图片路径
     */ filePath : string ; } ; export class TextEncryptTask implements TaskInterface { handle ( taskConfig ) { let texts = [ ] ; this . _collectTextFilePaths ( taskConfig . buildOutputResDirPath , texts ) ; console . log ( `文本处理：找到 ${ texts . length } 个文本文件` ) ; this . _encryptText ( texts ) ; console . log ( `文本处理：${ texts . length } 个文本文件已加密完成` ) ; } param dirName param texts private _collectTextFilePaths ( dirName , texts ) { if ( ! fs . existsSync ( dirName ) ) { throw new Error ( `${ dirName } 目录不存在` ) ; } let files = fs . readdirSync ( dirName ) ; files . forEach ( ( fileName ) => { let filePath = path . join ( dirName , fileName . toString ( ) ) ; let stat = fs . statSync ( filePath ) ; if ( stat . isDirectory ( ) ) { this . _collectTextFilePaths ( filePath , texts ) ; } else { let fileExtName = path . extname ( filePath ) ; switch ( fileExtName ) { case ".txt" : texts . push ( { type : TextType . TXT , filePath : filePath , } ) ; break ; case ".json" : texts . push ( { type : TextType . JSON , filePath : filePath , } ) ; break ; } } } ) ; } /**
     * 加密文本
     */ private _encryptText ( imgs ) { imgs . forEach ( ( imgObj ) => { let buffer = fs . readFileSync ( imgObj . filePath ) ; let encodeText = toBase64 ( buffer . toString ( ) ) ; encodeText += RandomUtil . randomString ( 10 ) ; fs . writeFileSync ( imgObj . filePath , encodeText ) ; } ) ; } }