Is there a way to rename a file in JSZip?

68 Views Asked by At

I have a file (or folder) in JSZip. I need to rename/move it.

const zip = new JSZip();
zip.file("file.txt", "File Content");
zip.rename("file.txt", "newname.txt"); // zip.rename doesn't exist

zip.rename doesn't exist, but is there any similar function? The only way that I can find is this answer, but it feels like it is too simple of a task to need that much code, and there might be a better way of doing it. If it matters, the code is running in a browser and not node.js.

1

There are 1 best solutions below

0
noname On BEST ANSWER

I'm not sure how reliable this is, but this seems to work. It just deletes the old file and makes a new one.

JSZip.prototype.renameAsync = async function rename(oldName, newName) {
    const old = this.file(oldName) || this.folder(oldName);
    const type = old.file ? "folder" : "file";

    if (type == "file") {
        const content = await old.async("uint8array");
        this.remove(old.name);
        this.file(newName, content);
    } else if (type == "folder") {
        const newFolder = this.folder(newName);
        old.forEach(async function(name, file) {
            const content = await file.async("uint8array");
            old.remove(name);
            newFolder.file(name, content);
        });
        this.remove(oldName);
    }
}

It's still pretty big, but it's better in my opinion.