ts-node 实现文件夹下xml文件转化为JSON格式,并压缩为ZIP

安装包

"dependencies": {
    "ts-node": "^10.9.1",
    "x2j": "0.0.1",
    "xml2js": "^0.6.2"
  },
  "devDependencies": {
    "@types/node": "^20.9.5"
  }

代码实现

/// <reference types="node" />

import { promisify } from 'util';//将基于回调的异步函数转换为返回 Promise 的异步函数

class ToolMainOne {
    private readonly XML_DIR: string;
    private readonly OUTPUT_DIR: string;
    private fs: any = require('fs')//读文件夹:readdir,//读文件readFile, 删除文件:unlink,//写文件wreatFile,获取文件目录信息;fs.stat,
    private path: any = require('path');//拼接地址 resolve,后缀名:extname,重命名:basename,
    private JSZip: any = require('jszip');//压缩
    private xml2js: any = require('xml2js')//解析为相应的 JavaScript 对象:parseStringPromise

    constructor(xmlDir: string, outputDir: string) {
        this.XML_DIR = xmlDir;
        this.OUTPUT_DIR = outputDir;
    }

    private async parseXmlToJson(xmlFilePath: string): Promise<void> {
        const parser = new this.xml2js.Parser();
        const readFile = promisify(this.fs.readFile);
        const writeFile = promisify(this.fs.writeFile);

        const xmlData = await readFile(xmlFilePath, { encoding: 'utf-8' });
        const jsonData = await parser.parseStringPromise(xmlData);

        // 重命名
        const jsonFileName = this.path.basename(xmlFilePath, this.path.extname(xmlFilePath)) + '.json';
        const jsonFilePath = this.path.resolve(this.OUTPUT_DIR, jsonFileName);
        try {
            await writeFile(jsonFilePath, JSON.stringify(jsonData), { encoding: 'utf-8' });
        } catch (err) { console.log(err); }

    }

    private async convertAllXmlToJson(xmlDirPath: string): Promise<void> {
        const readdir = promisify(this.fs.readdir);
        const stat = promisify(this.fs.stat);

        const files = await readdir(xmlDirPath);
        // console.log(files);


        for (const file of files) {
            const filePath = this.path.resolve(xmlDirPath, file);
            const fileStat = await stat(filePath);
            if (fileStat.isDirectory()) {
                await this.convertAllXmlToJson(filePath);
            } else if (fileStat.isFile() && this.path.extname(file) === '.xml') {
                await this.parseXmlToJson(filePath);
            }

        }


    }
    // private async clear(out: string): Promise<void> {
    //     const readdir = promisify(this.fs.readdir)
    //     const unlink = promisify(this.fs.unlink)
    //     const files = await readdir(out)
    //     for (let file of files) {
    //         const filePath = this.path.resolve(out, file)
    //         await unlink(filePath)
    //     }

    // }
    private async clearOutputDir(outputDirPath: string): Promise<void> {
        const readdir = promisify(this.fs.readdir);
        const unlink = promisify(this.fs.unlink);

        const files = await readdir(outputDirPath);
        for (const file of files) {
            const filePath = this.path.resolve(outputDirPath, file);
            await unlink(filePath);
        }
    }

    private async packJsonFilesToZip(outputDirPath: string): Promise<void> {
        const readdir = promisify(this.fs.readdir);
        const stat = promisify(this.fs.stat);
        const zip = new this.JSZip();

        const jsonFiles = await readdir(this.OUTPUT_DIR);
        for (const jsonFile of jsonFiles) {
            const jsonFilePath = this.path.resolve(this.OUTPUT_DIR, jsonFile);
            const jsonFileStat = await stat(jsonFilePath);

            if (jsonFileStat.isFile() && this.path.extname(jsonFile) === '.json') {
                const jsonData = await promisify(this.fs.readFile)(jsonFilePath, { encoding: 'utf-8' });
                zip.file(jsonFile, jsonData);
            }
        }

        const zipData = await zip.generateAsync({ type: 'nodebuffer' });
        const zipFilePath = this.path.resolve(outputDirPath, 'output.zip');
        await promisify(this.fs.writeFile)(zipFilePath, zipData);
    }

    async processXmlFiles(): Promise<void> {

        try {
            if (!this.fs.existsSync(this.OUTPUT_DIR)) {
                this.fs.mkdirSync(this.OUTPUT_DIR);
            }
            await this.clearOutputDir(this.OUTPUT_DIR);

            await this.convertAllXmlToJson(this.XML_DIR);
            await this.packJsonFilesToZip(this.OUTPUT_DIR);
        } catch (err) {
            console.log('出错', err);
        }

    }
}

// 使用示例
const tool = new ToolMainOne('../_xmls_weixin', 'output');
tool.processXmlFiles().then(() => {
    console.log('成功');
});

  • 7
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

新手村扛把子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值