>  기사  >  웹 프론트엔드  >  Node.js를 사용하여 간단한 파일 관리 시스템을 구축하는 방법

Node.js를 사용하여 간단한 파일 관리 시스템을 구축하는 방법

王林
王林원래의
2023-11-08 18:19:491465검색

Node.js를 사용하여 간단한 파일 관리 시스템을 구축하는 방법

Node.js는 JavaScript로 작성되었으며 개발자가 프런트엔드 및 백엔드 개발에 동일한 프로그래밍 언어를 사용할 수 있도록 하는 매우 인기 있는 서버 측 실행 환경입니다. Node.js의 효율성과 유연성은 Node.js를 웹 개발의 중요한 부분으로 만듭니다. 이 기사에서는 Node.js를 사용하여 간단한 파일 관리 시스템을 구축하는 방법을 알아봅니다.

이 기능을 구현하려면 Node.js의 기본 모듈 fs(파일 시스템)와 http를 사용하여 웹 서버를 생성해야 합니다. 먼저 명령줄에서 "npm init" 명령을 실행하여 package.json 파일을 생성한 다음 "npm install --save express body-parser ejs multer fs"를 통해 필요한 종속성 패키지를 설치해야 합니다.

먼저 app.js라는 Node.js 파일을 생성하겠습니다. 코드에서는 먼저 필요한 모듈과 미들웨어를 소개합니다.

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

여기에서는 express 프레임워크, body-parser 미들웨어 및 multer 미들웨어를 사용하여 파일 업로드 기능을 처리하고 ejs 템플릿 엔진을 사용하여 페이지를 렌더링합니다.

다음으로 정적 리소스 라우팅을 설정해야 합니다.

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

여기서 프로젝트의 정적 파일을 공용 폴더에 배치합니다.

POST 요청을 처리하려면 body-parser 미들웨어도 사용해야 합니다.

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

다음으로 파일 업로드 및 다운로드 요청을 처리하는 경로를 만듭니다.

//上传文件的路由
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는 여기에서 res를 사용하여 파일 업로드를 처리하는 데 사용됩니다. download() 메소드를 사용하여 파일을 다운로드합니다.

마지막으로 페이지를 렌더링하는 경로를 만듭니다.

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

여기에서는 업로드 폴더 아래의 모든 파일을 읽고 이를 템플릿 파일로 렌더링합니다.

다음으로 파일 목록과 파일 업로드 양식을 표시하기 위해 index.ejs 템플릿 파일을 생성해야 합니다.

<!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>

여기에서는 EJS 구문을 사용하여 파일 목록을 동적으로 생성하고 HTML 양식을 사용하여 파일을 업로드합니다.

마지막으로 서버를 시작합니다.

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

이제 Node.js를 사용하여 간단한 파일 관리 시스템 구축이 완료되었습니다. 브라우저에서 http://localhost:3000에 접속하면 효과를 볼 수 있습니다.

전체 코드는 다음과 같습니다.

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!');
});

지금까지 Node.js를 사용하여 간단한 파일 관리 시스템을 구축하는 과정을 완료했습니다. 이 예제를 통해 Node.js의 기본 모듈과 미들웨어 사용법을 더 잘 이해할 수 있습니다. .

위 내용은 Node.js를 사용하여 간단한 파일 관리 시스템을 구축하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.