mmu36478
mmu36478

Reputation: 1355

how to create folder in zip file archiver - node.js

I want to create a zip file and new folder in it. I created a zip file but couldn't create folders.

Here is my node.js code;

var archiver = require('archiver');
var zip = archiver('zip');

for(var i=0; i < files.length; i++){
     zip.append(new Buffer(files[i].data.buffer), { name: files[i].name } );    
}

For example I want to create folder as /first/second and add file in it.

.zip
  first(folder)
     second(folder)
        file

How can I do it?

Upvotes: 4

Views: 2890

Answers (2)

shaunhurryup
shaunhurryup

Reputation: 1

Maybe prefix attribute is more elegant than wiring the path to name attribute.

// node_modules/.store/@[email protected]/node_modules/@types/archiver/index.d.ts

interface EntryData {
    /** Sets the entry name including internal path */
    name: string;
    /** Sets the entry date */
    date?: Date | string | undefined;
    /** Sets the entry permissions */
    mode?: number | undefined;
    /**
     * Sets a path prefix for the entry name.
     * Useful when working with methods like `directory` or `glob`
     */
    prefix?: string | undefined;
    /**
     * Sets the fs stat data for this entry allowing
     * for reduction of fs stat calls when stat data is already known
     */
    stats?: fs.Stats | undefined;
}

// my code
archive.append(
  'Hello World',
  // same as => { name: 'resource/documents/xxx.json' },
  { prefix: 'resource/images', name: 'xxx.png' },
)         

https://i.sstatic.net/UMSXz.png

Upvotes: 0

mmu36478
mmu36478

Reputation: 1355

Actually, I just realize that it was quite simple by editing the name field in the following line;

zip.append(new Buffer(files[i].data.buffer), { name: files[i].name } );    

as

zip.append(new Buffer(files[i].data.buffer), { name: "/folderName/" + files[i].name } );    

You can replace /folderName/ with any filename that you want to create.

Upvotes: 7

Related Questions