我必须归档一个存在日志文件的目录(文件名的格式为i.e 2017-12-06.log
)。我必须归档除2017-12-06.log
.
我有一个所有日志文件都存在的日志目录和一个脚本create-zip.js
。当我使用 运行以下脚本时node create-zip.js
,它会创建目录/archive/<year>/<month_name>
并保存在此处logs.zip
文件夹。
一切都很好,除了当我提取时logs.zip
,我的存档日志文件在里面/archive/<year>/<month_name>/home/hotam/nodejs_archive_example/logs
,但我想要这些文件在里面/archive/<year>/<month_name>
。我google了很多,但找不到解决方案。提前致谢。
我有以下脚本(create-zip.js
):
'use strict';
var fs = require('fs'),
path = require('path'),
archiver = require('archiver'),
currDate = new Date(),
year = currDate.getFullYear(),
month = currDate.toLocaleString("en-us", { month: "long" }),
dir = path.join(__dirname + '/archive/' + year + '/' + month),
ignoredFile = currDate.getFullYear()+'-'+('0' + (currDate.getMonth() + 1)).slice(-2)+'-'+('0' + currDate.getDate()).slice(-2)+'.log';
//Function to create directories recursively
exports.createDir = function (dir) {
const splitPath = dir.split('/');
splitPath.reduce(function (dirPath, subPath) {
let currentPath;
if (subPath != '.') {
currentPath = dirPath + '/' + subPath;
if (!fs.existsSync(currentPath)) {
fs.mkdirSync(currentPath);
}
} else {
currentPath = subPath;
}
return currentPath
}, '');
};
exports.createDir(dir);
var output = fs.createWriteStream(path.join(dir, 'logs.zip'));
var archive = archiver('zip', {});
var logPath = __dirname + '/logs';
output.on('close', function () {
if (fs.existsSync(logPath)) {
fs.readdirSync(logPath).forEach(function (file, index) {
var curPath = logPath + "/" + file;
if (!fs.lstatSync(logPath).isFile()) {
// delete file
if(!(file == ignoredFile)) {
fs.unlinkSync(curPath);
}
}
});
}
});
output.on('end', function () {
console.log('Data has been drained');
});
archive.on('warning', function (err) {
if (err.code === 'ENOENT') {
console.log(err);
} else {
// throw error
console.log(err);
throw err;
}
});
archive.on('error', function (err) {
logger.error(err);
throw err;
});
archive.pipe(output);
//ignoring 2017-12-06.log
archive
.glob(__dirname + '/logs/**', {
ignore: [__dirname + '/logs/'+ignoredFile]
})
.finalize();