如何使用 JSZip 使用 node.js 中的缓冲区内容生成 zip 文件?

How to generate zip file using Buffer contents in node.js using JSZip?

我有一个字符串数组,应该将其写入 .txt 文件。我还需要使用 JSZip 将生成的 .txt 文件压缩为 .zip 格式。在客户端,我能够使用这个字符串数组生成一个 'text/plain' Blob,然后我使用 JSZip 将这个 Blob 压缩为 .zip 格式。我需要使用 node.js 在服务器端执行相同的操作,但我意识到 Blob 在 node.js 中不可用。我尝试使用 'Buffer' 而不是 Blob,我得到了一个压缩为 .zip 的二进制文件;我是 node.js 的初学者,无法理解 Buffer 的概念。我可以在 node.js 中创建一个 Blob 吗?或者我可以用 node.js 缓冲区执行相同的操作吗?

在客户端,我可以像这样从 Blob 内容生成 zip 文件,

//stringsArray is an array of strings
var blob = new Blob( stringsArray, { type: "text/plain" } );

var zip = new JSZip();
zip.file( 'file.txt' , blob );

zip.generateAsync( { type: 'blob', compression: 'DEFLATE' } )
.then( function( zipFile ){ 

    //do something with zipFile 

}, function( error ){ 

    console.log( 'Error in compression' );

} );

如何使用 Node.js 执行相同的操作?

我找到了解决办法。在我的代码中,我没有使用正确的方法将字符串数组转换为 node.js 缓冲区(我无法使用 JSZip 压缩缓冲区,因为缓冲区不正确)。 我尝试了以下代码,但它给了我一个不正确的缓冲区,

//stringsArray is an array of strings
var buffer = Buffer.from( stringsArray );

正确的方法是,我们必须先将每个字符串转换为缓冲区,然后通过附加所有这些子缓冲区来创建一个新缓冲区。我创建了一个自定义缓冲区构建器,它将通过向其附加字符串来构建 node.js 缓冲区。以下是我尝试过的新方法,它对我有用。

var CustomBufferBuilder = function() {

    this.parts = [];
    this.totalLength = 0;

}

CustomBufferBuilder.prototype.append = function( part ) {

    var tempBuffer = Buffer.from( part );
    this.parts.push( tempBuffer );
    this.totalLength += tempBuffer.length;
    this.buffer = undefined;

};

CustomBufferBuilder.prototype.getBuffer = function() {

    if ( !this.buffer ) {

       this.buffer = Buffer.concat( this.parts, this.totalLength );

    }
    return this.buffer;

};


var customBufferBuilder = new CustomBufferBuilder();
var stringsArray = [ 'hello ', 'world.', '\nThis ', 'is', ' a ', 'test.' ];//stringsArray is an array of strings
var len = stringsArray.length;
for( var i = 0; i< len; i++ ){

    customBufferBuilder.append( stringsArray[ i ] );

}

var bufferContent = customBufferBuilder.getBuffer();

var zip = new JSZip();
zip.file( 'test.txt', bufferContent, { binary : true } );
zip.generateAsync( { type : "nodebuffer", compression: 'DEFLATE' } )
.then( function callback( buffer ) {

    fs.writeFile( 'test.zip', buffer, function( err ){

        if( err ){

            //tasks to perform in case of error

        }
        else{

            //other logic

        }

    } );

}, function( e ) {

    //tasks to perform in case of error

} );

作为输出,我得到了压缩文件(test.zip)和里面的test.txt。 zip 文件中的 test.txt 文件包含以下文字, 'hello world.\nThis is a test.'.

感谢@BrahmaDev 花时间研究我的问题:)