node.jsfilezipunzip7zip

How to create password protect zip file in nodejs using node-7z-archive package


Please anyone guide me, how We can create password protected zip file and extract. using node-7z-archive https://www.npmjs.com/package/node-7z-archive actually I want to create password protect zip file with a folder

code to create a simple zip file:

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

const sourceFolder = 'create_zip'; // Replace with the actual folder path
const zipFileName = 'output.zip';

// Create a writable stream to the zip file
const output = fs.createWriteStream(zipFileName);

// Create a zip archive
const archive = archiver('zip', {
  zlib: { level: 9 } // Sets the compression level
});

// Pipe the archive to the output stream
archive.pipe(output);

// Add the entire folder to the archive
archive.directory(sourceFolder, false); // 'false' means no root directory in archive

// Finalize the archive
archive.finalize();

// Wait for the output stream to finish writing
output.on('close', () => {
  console.log('Zip archive created.');
});

// Handle errors during archiving
archive.on('error', (err) => {
  throw err;
});

please help me, How to create password protect zip file in nodejs using node-7z-archive package.


Solution

  • working code, but make sure download:7z https://www.7-zip.org/download.html as per system(window,mac,or any other) and setup environment

    <pre>
    import  Seven from 'node-7z'
    const options = {
      // Replace 'your-password' with the desired password for the archive.
      password: '1234',
    };
    
    const filesToCompress = 'create_zip'; // List of files to include in the archive.
    
    const archiveName = 'myArchive.7z'; // Specify the name of the archive file.
    
    // Create the 7z archive with a password.
    const myStream = Seven.add(archiveName, filesToCompress, options);
    
    // Handle progress events (optional)
    myStream.on('progress', (event) => {
      console.log(`Progress: ${event.percent}%`);
    });
    
    // Handle completion
    myStream.on('end', () => {
      console.log('7-Zip archive created with password.');
    });
    
    // Handle errors
    myStream.on('error', (error) => {
      console.error(`Error: ${error.message}`);
    });
    
    </pre>