Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,11 @@ zipdir('/path/to/be/zipped', function (err, buffer) {
// `buffer` is the buffer of the zipped file
});

zipdir('/path/to/be/zipped', { rootPath: 'archived' }, function (err, buffer) {
// Files and folders from `/path/to/be/zipped will`
// be stored in `archived/` in the output zip file.
});

zipdir('/path/to/be/zipped', { saveTo: '~/myzip.zip' }, function (err, buffer) {
// `buffer` is the buffer of the zipped file
// And the buffer was saved to `~/myzip.zip`
Expand Down Expand Up @@ -53,6 +58,7 @@ been saved to disk.

#### Options

* `rootPath` Folder path to create in the root of the zip file and place the input files and folder below it. Input files and folders will be placed directly to the zip file root by default.
* `saveTo` A path to save the buffer to.
* `filter` A function that is called for all items to determine whether or not they should be added to the zip buffer. Function is called with the `fullPath` and a `stats` object ([fs.Stats](http://nodejs.org/api/fs.html#fs_class_fs_stats)). Return true to add the item; false otherwise. To include files within directories, directories must also pass this filter.
* `each` A function that is called everytime a file or directory is added to the zip.
Expand Down
14 changes: 12 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,10 @@ module.exports = function zipWrite (rootDir, options, callback) {
function zipBuffer (rootDir, options, callback) {
var zip = new Zip();
var folders = {};

// Resolve the path so we can remove trailing slash if provided
rootDir = path.resolve(rootDir);

folders[rootDir] = zip;
folders[rootDir] = createRootFolder();

dive(rootDir, function (err) {
if (err) return callback(err);
Expand All @@ -47,6 +47,16 @@ function zipBuffer (rootDir, options, callback) {
}));
});

function createRootFolder () {
if (!options.rootPath) return zip;
var rootFolder = zip;
var splitPath = path.normalize(options.rootPath).split('/')
for (var i = 0; i < splitPath.length; ++i) {
rootFolder = rootFolder.folder(splitPath[i]);
}
return rootFolder;
}

function dive (dir, callback) {
fs.readdir(dir, function (err, files) {
if (err) return callback(err);
Expand Down