4

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?

2
  • are you sure that zip module you are using is meant for editing zip archives. this is what the documentation says "An implementation of unzip in JavaScript for Node" Commented Mar 15, 2017 at 13:49
  • I use for archiver for zipping yes. Commented Mar 16, 2017 at 6:41

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Perfectly working!
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.