Generate a password protected ZIP file in node.js

前端 未结 4 957
长情又很酷
长情又很酷 2021-01-17 16:15

I need to create a ZIP file in node.js, protected by a password.

I am using \"node-zip\" module, that unfortunately doesn\'t support password protection:

<         


        
4条回答
  •  天涯浪人
    2021-01-17 17:06

    The solution I'm using (I don't a better way to do it) is:

    var contenido1 = 'contenido super secreto';
    var contenido2 = 'otro contenido';
    var password = 'pass';
    var nombreFichero = 'fichero'
    
    var nodezip = new require('node-zip')();
    var fs = require("fs");
    nodezip.file('test1.txt', contenido1);
    nodezip.file('test2.txt', contenido2);
    var data = nodezip.generate({base64:false,compression:'DEFLATE'});
    fs.writeFile(nombreFichero + '.zip', data, 'binary');
    
    var exec = require('child_process').exec,
        child;
    
    child = exec('unzip ' + nombreFichero + '.zip -d ' + nombreFichero +
                 ' && zip -junk-paths --password ' + password + ' ' + nombreFichero + '-p.zip ' + nombreFichero + '/*' +
                 ' && rm -rf ' + nombreFichero + ' && rm -f ' + nombreFichero + '.zip',
      function (error, stdout, stderr) {
        console.log('stdout: ' + stdout);
        console.log('stderr: ' + stderr);
        if (error !== null) {
          console.log('exec error: ' + error);
        }
    });
    

    It generates a temporary zip file (without password), and then with several commands, upzip, zip with password and remove temporary files.

提交回复
热议问题