Home > Web Front-end > JS Tutorial > How to build a simple file management system using Node.js

How to build a simple file management system using Node.js

王林
Release: 2023-11-08 18:19:49
Original
1561 people have browsed it

How to build a simple file management system using Node.js

Node.js is a very popular server-side runtime environment. It is written in JavaScript and allows developers to use the same programming language for front-end and back-end development. The efficiency and flexibility of Node.js make it an important part of web development. In this article, we will learn how to use Node.js to build a simple file management system.

In order to achieve this function, we need to use the basic modules fs (file system) and http of Node.js to create a web server. First, you need to run the "npm init" command on the command line to generate a package.json file, and then install the required dependency packages through "npm install --save express body-parser ejs multer fs".

First, we will create a Node.js file named app.js. In the code, we first introduce the necessary modules and middleware:

const express = require('express');
const bodyParser = require('body-parser');
const multer = require('multer');
const fs = require('fs');
const ejs = require('ejs');
const app = express();
Copy after login

Here we use the express framework, body-parser middleware and multer middleware to handle the file upload function, and the ejs template engine to render the page.

Next, we need to set up static resource routing:

app.use(express.static(__dirname + '/public'));
Copy after login

Here we place the static files of the project in the public folder.

We also need to use the body-parser middleware to handle POST requests:

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
Copy after login

Next, we will create a route to handle file upload and download requests:

//上传文件的路由
app.post('/upload', upload.single('file'), (req, res) => {
  res.redirect('/');
});
 
//下载文件的路由
app.get('/download/:filename', (req, res) => {
  const { filename } = req.params;
  const filePath = `${__dirname}/uploads/${filename}`;
  res.download(filePath);
});
Copy after login

Multer is used here to process file uploads, and the res.download() method is used to download files.

Finally, we create a route to render the page:

app.get('/', (req, res) => {
  const filesPath = `${__dirname}/uploads`;
  const data = fs.readdirSync(filesPath);
  res.render('index', { files: data });
});
Copy after login

Here we read all the files in the uploads folder and render them into the template file.

Next, we need to create an index.ejs template file to display the file list and the form for uploading files:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>File Manager</title>
</head>
<body>
  <h1>Files List:</h1>
  <% for (let i = 0; i < files.length; i++) { %>
    <p><a href="/download/<%= files[i] %>"><%= files[i] %></a></p>
  <% } %>
 
  <hr>
 
  <h2>Upload File:</h2>
  <form method="post" action="/upload" enctype="multipart/form-data">
    <input type="file" name="file">
    <button type="submit">Upload</button>
  </form>
</body>
</html>
Copy after login

Here we use EJS syntax to dynamically generate the file list and use the HTML form to upload files.

Finally, we start the server:

app.listen(3000, () => {
  console.log('App listening on port 3000!');
});
Copy after login

Now we have completed building a simple file management system using Node.js, which can be accessed by visiting http://localhost:3000 in the browser See the effect.

The complete code is as follows:

const express = require('express');
const bodyParser = require('body-parser');
const multer = require('multer');
const fs = require('fs');
const ejs = require('ejs');
const app = express();
 
//设置静态资源路由
app.use(express.static(__dirname + '/public'));
 
//设置body-parser中间件
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
 
//设置存储文件的位置和文件名
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, 'uploads');
  },
  filename: (req, file, cb) => {
    const { originalname } = file;
    cb(null, originalname);
  }
});
 
const upload = multer({ storage });
 
//上传文件的路由
app.post('/upload', upload.single('file'), (req, res) => {
  res.redirect('/');
});
 
//下载文件的路由
app.get('/download/:filename', (req, res) => {
  const { filename } = req.params;
  const filePath = `${__dirname}/uploads/${filename}`;
  res.download(filePath);
});
 
//渲染页面的路由
app.get('/', (req, res) => {
  const filesPath = `${__dirname}/uploads`;
  const data = fs.readdirSync(filesPath);
  res.render('index', { files: data });
});
 
//设置模板引擎和模板文件夹位置
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
 
//启动服务
app.listen(3000, () => {
  console.log('App listening on port 3000!');
});
Copy after login

So far, we have completed the process of building a simple file management system using Node.js. Through this example, we can better understand Node. How to use basic modules and middleware of js.

The above is the detailed content of How to build a simple file management system using Node.js. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template