2017-09-25 92 views
0

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

在客户端,我可以生成斑点的内容是这样的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一样吗?

+1

此代码应该按原样运行。也许检查JSZip的文档,如果他们有不同的Node方法。 –

+0

@BrahmaDev,我在'node.js'中得到'Blob is not defined'错误 – HariV

+1

对不起,你必须使用Buffer。 该文档将是一个很好的研究点:https://stuk.github.io/jszip/documentation/api_jszip/generate_async.html –

回答

0

我找到了解决方案。在我的代码中,我没有使用正确的方法将字符串数组转换为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。\ n这是一个测试。'。

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

相关问题