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();
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'));
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 }));
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); });
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 }); });
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 id="Files-List">Files List:</h1> <% for (let i = 0; i < files.length; i++) { %> <p><a href="/download/<%= files[i] %>"><%= files[i] %></a></p> <% } %> <hr> <h2 id="Upload-File">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>
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!'); });
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!'); });
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Node.js can be used as a backend framework as it offers features such as high performance, scalability, cross-platform support, rich ecosystem, and ease of development.

The following global variables exist in Node.js: Global object: global Core module: process, console, require Runtime environment variables: __dirname, __filename, __line, __column Constants: undefined, null, NaN, Infinity, -Infinity

To connect to a MySQL database, you need to follow these steps: Install the mysql2 driver. Use mysql2.createConnection() to create a connection object that contains the host address, port, username, password, and database name. Use connection.query() to perform queries. Finally use connection.end() to end the connection.

There are two npm-related files in the Node.js installation directory: npm and npm.cmd. The differences are as follows: different extensions: npm is an executable file, and npm.cmd is a command window shortcut. Windows users: npm.cmd can be used from the command prompt, npm can only be run from the command line. Compatibility: npm.cmd is specific to Windows systems, npm is available cross-platform. Usage recommendations: Windows users use npm.cmd, other operating systems use npm.

Yes, Node.js is a backend development language. It is used for back-end development, including handling server-side business logic, managing database connections, and providing APIs.

Yes, Node.js can be used for front-end development, and key advantages include high performance, rich ecosystem, and cross-platform compatibility. Considerations to consider are learning curve, tool support, and small community size.

The main differences between Node.js and Java are design and features: Event-driven vs. thread-driven: Node.js is event-driven and Java is thread-driven. Single-threaded vs. multi-threaded: Node.js uses a single-threaded event loop, and Java uses a multi-threaded architecture. Runtime environment: Node.js runs on the V8 JavaScript engine, while Java runs on the JVM. Syntax: Node.js uses JavaScript syntax, while Java uses Java syntax. Purpose: Node.js is suitable for I/O-intensive tasks, while Java is suitable for large enterprise applications.

Node.js and Java each have their pros and cons in web development, and the choice depends on project requirements. Node.js excels in real-time applications, rapid development, and microservices architecture, while Java excels in enterprise-grade support, performance, and security.
