passionateLearner
passionateLearner

Reputation: 808

Compress directory with Node.js but exclude some files

I'm trying to compress a directory with Archiver. I want to exclude certain directories or files such as node_modules recursively.

For example, if I have a directory structure like this:

folder-to-compress
| node_modules
| sub-folder
  | ignored-file-name
  | included-file-name
| ignored-file-name

Below script only excludes from root level. So ignored-file-name in root will not be included in zip but sub-folder/ignored-file-name will be included. I'm wondering if there's a way to exclude recursively?

const fs = require('fs');
const archiver = require('archiver');

const output = fs.createWriteStream(__dirname);
const archive = archiver('zip', { zlib: { level: 9 } });

archive.pipe(output);

archive.glob('*/**', {
   cwd: __dirname,
   ignore: ['mode_modules', 'ignored-file-name', '*.zip']
});

archive.finalize();

Upvotes: 1

Views: 1836

Answers (1)

Matthew Horne
Matthew Horne

Reputation: 1

You can ignore files using glob patterns.

In your example:

ignore: ['mode_modules', 'ignored-file-name', '*.zip']

Should be (I corrected the misspelt node_modules)

ignore: ['node_modules/**', '**/ignored-file-name.*', '*.zip']

Whenever you want to exclude an entire directory, you will need to add a globstar to the end /**

Gulp has a good article explaining globs with additional resources at the bottom: https://gulpjs.com/docs/en/getting-started/explaining-globs/

Just a few points for completeness in case anyone comes across this post.

You're not defining a file name. You are just defining the directory.

const output = fs.createWriteStream(__dirname);

Should be

const output = fs.createWriteStream(__dirname + "/example.zip");

Which is how it is defined in the example: https://github.com/archiverjs/node-archiver#quick-start

Upvotes: 0

Related Questions