I want to read the contents of the file and use node-gzip.

Asked 1 years ago, Updated 1 years ago, 243 views

I am thinking of compressing the file with JavaScript and transferring it to the server in node-gzip.
On this page, as shown below (see ), there is a description of the text as input.
(Here's 'Hello World')
I replaced 'Hello World' like fileA.txt because I want to specify a file for this text and compress it, but I got an error.
I'm sorry this is a very rudimentary question, but I'd appreciate it if you could let me know.

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

javascript nodejs gzip

2022-11-08 19:57

1 Answers

node-gzip is

according to README

Buffer|TypedArray|DataView|ArrayBuffer|string

Accept the .The fs.readFile returns the contents of the file with either string or Buffer, so that's fine.

constfs=require('node:fs/promises');
const {gzip,ungzip} = require('node-gzip');

;(async function(){
    const data = wait fs.readFile("hello.txt");
    const compressed = wait gzip(data);
    constdecompressed=awaitungzip(compressed);
    console.log(decompressed.toString());
})()

If you are using a version of Node.js where the prefix node: cannot be used, specify the module without the prefix as shown below.However, it does not delete /promises.

constfs=require('fs/promises');

If you want to move on the client (browser) side

That's impossible.
The Node.js API is not implemented on the client (browser). Therefore, neither the zlib module nor the node-gzip module that depends on it will work. The fs module is easy to understand considering security and privacy. It's a big deal if you can read and write files on your machine by specifying a file name.

For that reason, we have no choice but to give up the structure according to the question.However,

  • Have the user submit the file
  • In that case, have it compressed

It is not entirely impossible thatTry searching with keywords such as "POST files (and data)". (You should forget about compression and complete it.)


2022-11-08 23:46

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.