安装包
"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('成功');
});