这是代码
import JSZip = require('jszip');
import crypto = require('crypto');
let zip = new JSZip();
zip.file("hello.txt", "Hello World\n");
zip.folder("nested").file("hello.txt", "Hello World\n");
zip.generateAsync({
type: 'nodebuffer',
mimeType: 'application/epub+zip',
compression: 'DEFLATE',
compressionOptions: {
level: 9
},
})
.then(buf => {
const md5 = crypto.createHash('md5');
let result = md5.update(buf).digest('hex');
console.dir(result);
})
;
如果运行此代码两次,将得到 diff md5
当上下文相同时,如何使其成为相同的缓冲区
最佳答案
问题在于 JSZip 创建的 .zip 存档条目将具有与其关联的文件修改时间戳。这会导致不同时间生成的文件之间存在微小差异(通常是几个字节)。因此,我们需要手动指定文件时间戳,并确保在 .zip 存档中仅创建虚拟文件夹。
这种方法应该适合您(每次给出相同的 MD5 哈希值):
import JSZip = require('jszip');
import crypto = require('crypto');
// You must fix the date (set to the same value) so that the zip archive timestamps will be equal.
// Also we must create virtual folders or they will be assigned timestamps too, resulting in a different hash.
const options = { date: new Date('2019-07-24 06:00:00Z'), createFolders: false};
zip.file("hello.txt", "Hello World\n", options);
zip.file("nested/hello.txt", "Hello World\n", options);
zip.generateAsync({
type: 'nodebuffer',
mimeType: 'application/epub+zip',
compression: 'DEFLATE',
compressionOptions: {
level: 9
},
})
.then(buf => {
const md5 = crypto.createHash('md5');
let result = md5.update(buf).digest('hex');
console.dir(result);
})
;
关于javascript - 如何让jszip生成相同的缓冲区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57175871/