3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Node.jsで文字列を圧縮

Posted at

Node.jsのビルドインモジュールを使って文字列を圧縮 (gzip)

const Buffer = require('buffer').Buffer;
const zlib = require('zlib');

/**
 * 圧縮
 */
function gzip(str){
    const content = encodeURIComponent(str) // エンコード
    const result = zlib.gzipSync(content)   // 圧縮
    const value = result.toString('base64') // Buffer => base64変換
    return value;
}
/**
 * 解凍
 */
function unzip(value){
    const buffer = Buffer.from(value, 'base64')              // base64 => Bufferに変換
    const result = zlib.unzipSync(buffer)                    // 復号化
    const str = decodeURIComponent(result).toString('utf-8') // デコード
    return str;
}

const str = `あいうえおあいうえおあいうえおあいうえおあいうえおあいうえおあいうえおあいうえおあいうえおあいうえおあいうえおあいうえおあいうえおあいうえお`
const str1 = gzip(str);
const str2 = unzip(str1);

console.log(str)
console.log(str1)
console.log(str2)

圧縮前

あいうえおあいうえおあいうえおあいうえおあいうえおあいうえおあいうえおあいうえおあいうえおあいうえおあいうえおあいうえおあいうえおあいうえおあいうえおあいうえおあいうえおあいうえおあいうえおあいうえお

圧縮後

H4sIAAAAAAAAA1N1NVa1MFS1MFKFMkxgDDMYwwLGcFQdVTyqmBqKATEK0v52AgAA

解凍

あいうえおあいうえおあいうえおあいうえおあいうえおあいうえおあいうえおあいうえおあいうえおあいうえおあいうえおあいうえおあいうえおあいうえおあいうえおあいうえおあいうえおあいうえおあいうえおあいうえお

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?