I am using adm-zip in NodeJS but my files in compressed packages have always got the timestamp of zip creation. I would like that files keep the original date and hour, not the moment when I create the zip. Which option should I apply to zip.addFile(...) ? I checked the source but I don't understand how it sets the attributes. Thanks.
zip.addFile(filename, content, comment, date) doesn't work
You’re right — many versions of adm-zip
ignore the date
parameter in zip.addFile(...)
, and your ZIP entries always end up with the current timestamp.
Instead of trying to pass the date as a fourth argument (which is unreliable), you can manually set the correct timestamp on the internal ZIP entry using header.time
:
const zip = new AdmZip();
const filePath = 'your-file.txt';
const content = fs.readFileSync(filePath);
const stats = fs.statSync(filePath); // original modified time
// Add the file to the ZIP
const entry = (zip.addFile as any)('your-file.txt', content);
// Override the modified time in ZIP metadata
entry.header.time = stats.mtime;
zip.writeZip('output.zip');
async function zipFiles(folderPath: string): Promise<Buffer> {
const zip = new AdmZip();
function addFilesRecursively(currentPath: string, relativePath = '') {
const entries = fs.readdirSync(currentPath, { withFileTypes: true });
for (const entry of entries) {
const fullPath = path.join(currentPath, entry.name);
const zipEntryPath = path.join(relativePath, entry.name);
if (entry.isDirectory()) {
addFilesRecursively(fullPath, zipEntryPath);
} else {
const content = fs.readFileSync(fullPath);
const stats = fs.statSync(fullPath);
// Add file to the ZIP
const zipEntry = (zip.addFile as any)(zipEntryPath, content);
// Override timestamp
if (zipEntry && zipEntry.header) {
zipEntry.header.time = stats.mtime;
}
}
}
}
addFilesRecursively(folderPath);
return zip.toBuffer();
}