Home / Article Detail

Node implementation of .zip packaging

📅 Dec 28, 2023✍️ lllomh

    Next.js build to .next.zip from node.

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

    // Set the directory to be packed and the name of the output zip file
    const sourceDirectory = '.next';
    const outputZipFile = '.next.zip'; // Modify the output zip file name

    // Delete the existing .next.zip file
    if (fs.existsSync(outputZipFile)) {
    fs.unlinkSync(outputZipFile);
    console.log(`Deleted ${outputZipFile} file`);
    }

    // Creating an Output Stream
    const output = fs.createWriteStream(outputZipFile);
    const archive = archiver('zip', {
    zlib: { level: 9 } // Setting the compression level
    });

    // Pipes the output stream to a zip file
    archive.pipe(output);

    // Adding an entire directory to a zip file
    archive.directory(sourceDirectory, '.next');

    // Completing the zip file
    archive.finalize();

    output.on('close', () => {
    console.log(`${outputZipFile} file was created,in total ${archive.pointer()} byte`);
    });

    output.on('end', () => {
    console.log('All data has been written to the file');
    });

    archive.on('warning', (err) => {
    if (err.code === 'ENOENT') {
    console.warn(err.message);
    } else {
    throw err;
    }
    });

    archive.on('error', (err) => {
    throw err;
    });


    Then will get .next.zip file.