2017-07-21 91 views
5

いくつかのデータを書き込み可能なストリームに圧縮したいと思います。node.js ZIPをメモリに圧縮する

目的はすべてメモリ上で行い、ディスク上に実際のzipファイルを作成しないことです。

テストの場合のみ、私はディスク上にZIPファイルを作成しています。しかし、私が開こうとするとoutput.zip次のエラーが表示されます: "アーカイブは不明な形式か破損しています"。 (Windows 7のWinZipとMACの同様のエラー)

何が間違っていますか?

const fs = require('fs'), 
    archiver = require('archiver'), 
    streamBuffers = require('stream-buffers'); 

let outputStreamBuffer = new streamBuffers.WritableStreamBuffer({ 
    initialSize: (1000 * 1024), // start at 1000 kilobytes. 
    incrementAmount: (1000 * 1024) // grow by 1000 kilobytes each time buffer overflows. 
}); 

let archive = archiver('zip', { 
    zlib: { level: 9 } // Sets the compression level. 
}); 
archive.pipe(outputStreamBuffer); 

archive.append("this is a test", { name: "test.txt"}); 
archive.finalize(); 

outputStreamBuffer.end(); 

fs.writeFile('output.zip', outputStreamBuffer.getContents(), function() { console.log('done!'); }); 
+1

は「私が間違って何をしているのですか?」あなたが得ている結果とあなたが期待している結果とどのように異なるかを教えない限り、その質問に答えることはできません。 –

+0

あなたは正しいです。私は私の質問を更新しました。 thx –

答えて

4

コンテンツが出力ストリームに書き込まれるのを待っていません。

あなたのコードからコメントアウトoutputStreamBuffer.end();と次のように変更...

outputStreamBuffer.on('finish', function() { 
    fs.writeFile('output.zip', outputStreamBuffer.getContents(), function() { 
     console.log('done!'); 
    }); 
}); 
+0

これは動作しません。 ZIPファイルを開くと、output.zip.cpgzという別のファイルが表示されます。 –

+3

私の答えは@YoniMayerに更新されました。それを試してみてください。私のために働いた。 –

+1

@Matt 'finish'は 'end'の後に呼び出されるので、最終イベントです。あなたは '終わり'を使いたいと思う特別な理由はありますか? –

関連する問題