nodejs文件相关操作 (读取、复制、删除、压缩、解压缩等)
具体方法
读取需要解析的xml文件列表
/**
* 读取需要解析的xml文件列表
* @param {string} filePath 源文件夹路径
*/
fileHelper.findJsonFile = filePath => {
const jsonFiles = []
const files = fs.readdirSync(filePath)
files.forEach(function (item, index) {
const fPath = path.join(filePath, item)
const susbFiles = fs.readdirSync(fPath)
susbFiles.forEach(function (_item) {
// const reg = /\\d{4}_\\d{4}_\\d{5}_\\d{6}_\\d{8}.xml/
const reg = /^SASP_SDAS_DAILY_REPORT_/
const reg1 = /.xml$/
if (reg.test(_item) && reg1.test(_item) && !_item.includes('EN')) {
const dirPath = path.join(fPath, _item)
jsonFiles.push({ date: item, inputPath: dirPath })
}
})
})
return jsonFiles
}
解析xml文件
/**
* 解析xml文件
* @param {string} filePath xml文件
*/
fileHelper.parseXml = function (filePath) {
const xml = fs.readFileSync(filePath, 'utf-8')
const result1 = convert.xml2json(xml, { compact: true, spaces: 4 })
return JSON.parse(result1)
}
word转换为xml文件夹
/**
* word转换为xml文件夹
* @param {string} inputPath 源文件
* @param {string} outPutPath 目标文件夹
*/
fileHelper.parseWord = function (inputPath, outPutPath) {
inputPath = './test.docx'
outPutPath = './template/test'
const zip = new AdmZip(inputPath)
// 将该docx解压到指定文件夹result下
zip.extractAllTo(outPutPath, /* overwrite */ true)
fs.unlink(inputPath)
}
读取xml文件并获取替换的数据
/**
* 读取xml文件
* @param {string} fileName 源文件xml
* @param {[]} data 数据
*/
fileHelper.readFile = async function (fileName, data) {
try {
const result = await fs.promises.readFile(fileName)
let str = result.toString()
data.forEach(item => {
str = str.replace(item.sourceRegx, item.targetStr)
})
return str
} catch (err) {
console.log('readFile:', err)
return err
}
}
读取txt文件
/**
* 读取txt文件
* @param {string} fileName 源文件txt
*/
fileHelper.readTxtFile = async function (fileName) {
let content = fs.readFileSync(fileName, { encoding: 'binary' })
// iconv解决中文乱码
content = iconv.decode(content, 'GBK').toString()
return content
}
读取json文件
/**
* 读取json文件
* @param {string} fileName 源文件json
*/
fileHelper.readJsonFile = async function (fileName) {
return new Promise((resolve, reject) => {
let content = fs.readFileSync(fileName, 'utf8')
content = JSON.parse(content)
// return content
resolve(content)
})
}
写入文件,替换文件中指定的字符串
/**
* 写入文件,替换文件中指定的字符串
* @param {string} fileName 源文件xml
* @param {[]} data 数据
*/
fileHelper.writeFiles = async function (fileName, str) {
console.log('替换数据')
// 如果第三个参数不写就是直接覆盖内容
await fs.promises.writeFile(fileName, str)
}
xml文件夹生成对应word文档
/**
* xml文件夹生成对应word文档
* @param {string} inputPath 源文件夹(xml)
* @param {string} outputPath 目标文件
*/
fileHelper.generateWord = async function (inputPath, outputPath) {
try {
const zip = new AdmZip()
console.log('inputPath:', inputPath)
zip.addLocalFolder(inputPath)
await zip.writeZip(outputPath)
} catch (error) {
console.log('生成word,err:', error)
}
}
文件夹复制
/**
* 文件夹复制
* @param {string} src 源文件夹
* @param {string} dest 目标文件夹
*/
fileHelper.CopyDirectory = function (src, dest) {
if (!fs.existsSync(dest)) {
fs.mkdirSync(dest)
}
if (!fs.existsSync(src)) {
return false
}
// 拷贝新的内容进去
const dirs = fs.readdirSync(src)
dirs.forEach(function (item) {
const itemPath = path.join(src, item)
const temp = fs.statSync(itemPath)
if (temp.isFile()) {
// 是文件
// console.log("Item Is File:" + item);
fs.copyFileSync(itemPath, path.join(dest, item))
} else if (temp.isDirectory()) {
// 是目录
// console.log("Item Is Directory:" + item);
fileHelper.CopyDirectory(itemPath, path.join(dest, item))
}
})
}
删除文件夹下内容
/**
* 删除文件夹下内容
* @param {string} path 文件夹
*/
fileHelper.delDir = function (path) {
try {
if (!fs.existsSync(path)) {
return true
}
if (fs.statSync(path).isDirectory()) {
const files = fs.readdirSync(path)
files.forEach((file, index) => {
const currentPath = path + '/' + file
if (fs.statSync(currentPath).isDirectory()) {
// 如果条件为真 说明 currentPath是一个目录
fileHelper.delDir(currentPath)
} else {
// currentPath说明是一个文件
fs.unlinkSync(currentPath)
if (fs.readdirSync(path).length <= 0) {
fs.rmdirSync(path)
}
}
})
} else {
fs.unlinkSync(path)
fs.rmdirSync(path)
}
return true
} catch (e) {
console.log(e)
return false
}
}
相关知识
1.adm-zip:创建和提取zip文件
var admZip = require('adm-zip');
var iconv = require('iconv-lite');
/**
* unzip
* zipFile,待解压缩的zip文件
* destFolder,解压缩后存放的文件夹
*/
function unzip(zipFile, destFolder){
var zip = new admZip(zipFile);
var zipEntries = zip.getEntries();
for(var i=0; i<zipEntries.length; i++){
var entry = zipEntries[i];
entry.entryName = iconv.decode(entry.rawEntryName, 'gbk');
}
zip.extractAllTo(destFolder, true);
}
/**
* zip file
* sourceFile,待压缩的文件
* destZip,压缩后的zip文件
*/
function zipFile(sourceFile, destZip){
var zip = new admZip();
zip.addLocalFile(sourceFile);
zip.writeZip(destZip);
}
/**
* zip folder
* sourceFolder,待压缩的文件夹
* destZip,压缩后的zip文件
*/
function zipFolder(sourceFolder, destZip){
var zip = new admZip();
zip.addLocalFolder(sourceFolder);
zip.writeZip(destZip);
}
2.xml-js:XML文本和JavaScript对象/JSON文本之间的转换器。
const xml = fs.readFileSync(filePath, 'utf-8')
const result1 = convert.xml2json(xml, { compact: true, spaces: 4 })
return JSON.parse(result1)
3.iconv-lite:转换文件编码
var iconv = require('iconv-lite');
var fs = require('fs');
var fileStr = fs.readFileSync('input.txt',{encoding:'binary'});
var buf = new Buffer(fileStr,'binary');
var str = iconv.decode(buf,'GBK');
console.log(str);
4.docx和doc的区别:
docx格式与doc格式都是word文本格式,但是二者的差距实际上是很大的,docx和doc的区别显著的一点就是体积大小的不同。docx格式就是一个zip文件,我们可以拿winrar打开docx文件,得到一堆的文件,很类似android程序或者win7桌面窗体的源码,你在里面可以找到各种配置文件,文本文件和媒体文件。