Use Node.js+Vue.js to build file compression applications

青灯夜游
Release: 2020-11-25 17:56:11
forward
3107 people have browsed it

Use Node.js+Vue.js to build file compression applications

Related recommendations: "node js tutorial"

Node.js provides us with a module to assist in file compression. In this article, we will build an application where users can upload a file they want to compress and then download a compressed version of the file using the Node.js Zlib module.

Prerequisites

To continue with this tutorial, you need to have the following qualifications:

  • Familiar with HTML, CSS and Javascript (ES6)
  • VS Code or any code editor installed on your development machine
  • Have Postman installed on your development machine
  • The basics of Vue and Node.js

Setup Project

We will start by building the backend, which is the foundation of our application.

On the desktop, create a folder for the application, name itcompressor, and set up a new Node by runningnpm init -y. js project.

We write the back-end service first, so create anotherserverdirectory in the project.

Now we need to install the necessary packages for the application:

  • koa, koa-router: This will help For setting up our server and routing
  • nodemon: When we make changes to the application, Nodemon will restart our server
  • multer:Middleware for uploading files
  • cors:Help adding headers to proxy requests

To install them all, install them in the ## Run the following command in the ##serverdirectory:

npm i --save koa koa-router nodemon multer cors
Copy after login
After completing the installation, create an

index.jsfile in theserverdirectory. This is what we will Where the backend code is written.

Open the folder using VS Code. Before we start, we create a

.gitignorefile and addnode_modulesto it, this will prevent thenode_modulesfolder from being added to git.

Let's go ahead and create a simple Koa.js server and then configure our packages:

const express = require('express'); const multer = require('multer'); const zlib = require('zlib'); const cors = require('cors'); const fs = require('fs'); const path = require('path'); const app = express(); app.use(cors()); //multer const storage = multer.memoryStorage(); const upload = multer({ storage: storage, }); app.listen(3000, () => { console.log('App is runnuing on port 3000'); });
Copy after login
We first ask for the packages we have installed, such as Express, Multer, and Cors. Then, we create an instance of Express and save it in a variable. We use an Express instance to configure our

corsas middleware.

We also need some core Node.js modules, such as

zlib, which we will use to do the actual compression. We then use an instance of Express to create a server that will listen on port3000.

Next, we will create a route that will receive a file and return a compressed file.

Zlib has many compression methods, but in this article, we will use the

gzipmethod.

app.post("/compress", upload.single("file"), async (req, res) => { try { const destination = `compressed/${req.file.originalname}.gz`; let fileBuffer = req.file.buffer; await zlib.gzip(fileBuffer, (err, response) => { if (err) { console.log(err); } fs.writeFile(path.join(__dirname, destination), response, (err, data) => { if (err) { console.log(err); } res.download(path.join(__dirname, destination)); }); }); } catch (err) { console.log(err); res.json(err); } });
Copy after login
We define the

/compressroute, which is aPOSTrequest, and then pass the Multer middleware in that route. OurMultermiddleware will return the file buffer, which is stored in thefileBuffervariable.

For testing, we create a

compresseddirectory and save the compressed files in it.

We will use the Multer middleware to get the name of the file we want to compress so that we can save it to our

compresseddirectory.

const destination = `compressed/${req.file.originalname}.gz`;
Copy after login
We use the Zlib method

gzipto compress the file, which takesfileBufferas the first parameter and then a callback function as the second parameter. The callback function consists of any possible errors and compressed responses.

After getting the Zlib response we create a file and save the response in the

compresseddirectory, the file will have the.gzfile extension because it is used Identifies Zlib compression.

Now we can test our application on Postman before starting the frontend, I will zip the

package.lock.jsonfile, its size is 48kb.

Use Node.js+Vue.js to build file compression applications

Compressed file can get 11kb.

Use Node.js+Vue.js to build file compression applications

Now that our backend is ready, we can set up the user interface for our application.

Let's create a

clientdirectory inside thecompressorroot directory. In theclientdirectory, create two files:index.htmlandmain.js.

We will start by defining the user interface for the application.

We will build an HTML 5 template file, and then add the vuei.js script, Bootstrap CSS CDN and Axios scripts to the template header. We will then add the

main.jsfile at the end of the body tag.

nbsp;html>   Vue Compressor    

压缩

Copy after login

对于此应用程序,用户将通过拖放添加其文件。让我们为我们的应用程序定义一个简单的用户界面。

修改模板为:

nbsp;html>   Vue Compressor     

在这里拖放

Copy after login
  • FileName -> File Size

你可以使用任何实时服务器运行你的应用程序,这里我使用live-server

Use Node.js+Vue.js to build file compression applications

拖放功能

我们先在main.js文件中定义我们的Vue.js实例。然后,我们将创建一个state来保存我们的文件。

const app = new Vue({ el: '#app', data: { files: [], loading:false }, methods: { addFile(e) { }, removeFile(file) { }, compressFile() { } } })
Copy after login

在Vue中实现拖放,我们需要添加一个@drop事件来选择我们的文件,还有一个v-cloak属性,这个属性用于在应用加载之前隐藏{{tags}}

在这里拖放

Copy after login

@drop事件监听addFile方法,我们必须定义:

addFile(e) { let files = e.dataTransfer.files; [...files].forEach(file => { this.files.push(file); console.log(this.files) }); }
Copy after login

使用这种方法,放置在框中的所有文件都将记录在我们的控制台上。

但是,我们想在框内显示文件,因此我们必须将

  • 元素修改为:

    
            
    Copy after login
  • {{ file.name }}-{{ file.size }} kb

    这样,每当我们将文件放入框中时,都会显示文件名和大小。

    我们可以通过向X按钮添加点击事件来添加额外的功能,以从框中删除文件:@click = ‘removeFile(file)’

    然后,我们定义removeFile方法:

    removeFile(file) { this.files = this.files.filter(f => { return f != file; }); },
    Copy after login

    让我们定义压缩函数,该函数将压缩所选文件,这就是Axios的作用所在。我们将向我们在后端定义的/compress路由发出请求:

    compressFile() { this.loading = true; let formdata = new FormData(); formdata.append('file', this.files[0]) axios.post('http://localhost:3000/compress', formdata, { responseType: 'blob' }).then(response => { let fileURL = window.URL.createObjectURL(new Blob([(response.data)])) let fileLink = document.createElement('a'); fileLink.href = fileURL; fileLink.setAttribute('download', `${this.files[0].name}.gz`); document.body.appendChild(fileLink); fileLink.click(); this.loading = false; }).catch(err => { this.loading = false; console.log(err) }) }
    Copy after login

    我们使用FormData上传文件。上载文件后,后端会压缩文件并将压缩后的文件返回给我们。

    我们使用URL.createObjectURL创建一个DOMstring,其中包含表示给定对象的URL。然后,我们从后端下载给定的数据。

    现在,我们需要在compress按钮中添加一个click事件,以侦听我们创建的方法:

    Copy after login

    单击我们的压缩按钮将触发文件下载:

    Use Node.js+Vue.js to build file compression applications

    就是这样!

    我们只是建立了一个简单的压缩应用程序。最后我们很想添加一个简单的方法,通过创建一个Vue.js过滤器,将我们的文件大小以千字节为单位进行格式化。

    filters: { kb(val) { return Math.floor(val / 1024); } },
    Copy after login

    在模板中使用

    {{ file.size | kb }} kb
    Copy after login

    这会将文件的大小格式化为更易读的格式。

    源码

    Node.js使文件压缩变得容易。它可以进一步用于压缩HTTP请求和响应,以提高应用程序性能。要获得更多Zlib功能,可以查看Zlib上的Node.js文档。

    源代码:https://github.com/dunizb/CodeTest/tree/master/Node/compressor

    原文地址:https://blog.logrocket.com/build-a-file-compression-application-in-node-js-and-vue-js/

    相关推荐:

    2020年前端vue面试题大汇总(附答案)

    vue教程推荐:2020最新的5个vue.js视频教程精选

    更多编程相关知识,请访问:编程入门!!

    The above is the detailed content of Use Node.js+Vue.js to build file compression applications. For more information, please follow other related articles on the PHP Chinese website!

  • Related labels:
    source:segmentfault.com
    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!