Search code examples
javascriptnode.jscompressiongzip

How to use "node-gzip" for file instead of text


I am learning how to compress the file by JavaScript by using "node-gzip"(https://www.npmjs.com/package/node-gzip). "node-gzip" README said the following when you can compressed text. So I tried to change from 'Hello World' to fileA(ascii or binary file) , but it does not work.

How can I compress the file by usign "node-gzip".

** Nodejs and node-gzip is installed.

<"node-gzip" README>

const {gzip, ungzip} = require('node-gzip');
const compressed = await gzip('Hello World');
const decompressed = await ungzip(compressed);
console.log(decompressed.toString()); //Hello World

Solution

  • I believe your goal is as follows.

    • You want to use a text file instead of 'Hello World' in your showing script.

    In this case, how about the following modification?

    Modified script:

    Please set your text filename with the path to the following script.

    const text = fs.readFileSync("./sample.txt"); // or const text = fs.readFileSync("./sample.txt", "utf-8");
    const compressed = await gzip(text);
    const decompressed = await ungzip(compressed);
    console.log(decompressed.toString());
    
    • In this case, please include const fs = require("fs");.