diff --git a/README.md b/README.md index 398087b..55bfdff 100644 --- a/README.md +++ b/README.md @@ -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` @@ -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. diff --git a/index.js b/index.js index 3fa84a0..3c65c90 100644 --- a/index.js +++ b/index.js @@ -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); @@ -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);