Created
May 5, 2025 10:17
-
-
Save sunmeat/c93eec8384b169d5ad167d3d352ff199 to your computer and use it in GitHub Desktop.
работа с файлами Node.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
1. установить node.js по ссылке https://nodejs.org/en | |
2. выполнить такие команды в терминале git bash: | |
cd C:/Users/Alex/Desktop | |
mkdir file-server | |
cd file-server | |
npm init -y | |
npm install express multer | |
mkdir public | |
mkdir uploads | |
3. положить в корневую папку проекта файл server.js с таким содержимым: | |
const fs = require('fs').promises; | |
const path = require('path'); | |
const express = require('express'); | |
const multer = require('multer'); | |
const app = express(); | |
const port = 3000; | |
// настройка директории для хранения файлов | |
const uploadDir = path.join(__dirname, 'uploads'); | |
fs.mkdir(uploadDir, { recursive: true }).catch(console.error); | |
// настройка multer для загрузки файлов | |
const storage = multer.diskStorage({ | |
destination: (req, file, cb) => { | |
cb(null, uploadDir); | |
}, | |
filename: (req, file, cb) => { | |
cb(null, file.originalname); | |
} | |
}); | |
const upload = multer({ storage }); | |
// middleware для обработки JSON, форм и статических файлов | |
app.use(express.json()); | |
app.use(express.urlencoded({ extended: true })); | |
app.use('/uploads', express.static(uploadDir)); | |
app.use(express.static('public')); // Папка для index.html | |
// cохранение текстового файла | |
app.post('/save-file', async (req, res) => { | |
try { | |
const { filePath, content } = req.body; | |
if (!filePath || !content) { | |
return res.status(400).json({ error: 'Укажите путь и содержимое файла' }); | |
} | |
const safePath = path.join(uploadDir, filePath); | |
if (!safePath.startsWith(uploadDir)) { | |
return res.status(400).json({ error: 'Недопустимый путь' }); | |
} | |
await fs.writeFile(safePath, content, 'utf8'); | |
res.status(200).json({ message: `Файл успешно сохранен по пути: ${safePath}` }); | |
} catch (err) { | |
console.error(err); | |
res.status(500).json({ error: `Ошибка при сохранении файла: ${err.message}` }); | |
} | |
}); | |
// загрузка файла | |
app.post('/upload-file', upload.single('file'), (req, res) => { | |
try { | |
if (!req.file) { | |
return res.status(400).json({ error: 'Файл не загружен' }); | |
} | |
res.status(200).json({ message: `Файл успешно загружен: ${req.file.path}` }); | |
} catch (err) { | |
console.error(err); | |
res.status(500).json({ error: `Ошибка при загрузке файла: ${err.message}` }); | |
} | |
}); | |
// чтение файла | |
app.get('/load-file', async (req, res) => { | |
try { | |
const { filePath } = req.query; | |
if (!filePath) { | |
return res.status(400).json({ error: 'Укажите путь к файлу' }); | |
} | |
const safePath = path.join(uploadDir, filePath); | |
if (!safePath.startsWith(uploadDir)) { | |
return res.status(400).json({ error: 'Недопустимый путь' }); | |
} | |
const content = await fs.readFile(safePath, 'utf8'); | |
res.status(200).json({ content }); | |
} catch (err) { | |
console.error(err); | |
res.status(500).json({ error: `Ошибка при чтении файла: ${err.message}` }); | |
} | |
}); | |
// запуск сервера | |
app.listen(port, () => { | |
console.log(`Сервер запущен на http://localhost:${port}`); | |
}); | |
=================================================================================================== | |
4. положить в папку public файл index.html с таким содержимым: | |
<!DOCTYPE html> | |
<html lang=""> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<title>Работа с файлами</title> | |
<style> | |
body { | |
font-family: Arial, sans-serif; | |
max-width: 800px; | |
margin: 0 auto; | |
padding: 20px; | |
background-color: #f4f4f9; | |
} | |
h2 { | |
color: #333; | |
border-bottom: 2px solid #6200ea; | |
padding-bottom: 5px; | |
} | |
.section { | |
background: white; | |
padding: 20px; | |
margin-bottom: 20px; | |
border-radius: 8px; | |
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); | |
} | |
label { | |
display: block; | |
margin-bottom: 5px; | |
font-weight: bold; | |
color: #444; | |
} | |
input[type="text"], | |
textarea, | |
input[type="file"] { | |
width: 100%; | |
padding: 10px; | |
margin-bottom: 10px; | |
border: 1px solid #ccc; | |
border-radius: 4px; | |
box-sizing: border-box; | |
} | |
textarea { | |
height: 100px; | |
resize: vertical; | |
} | |
button { | |
background-color: #6200ea; | |
color: white; | |
padding: 10px 20px; | |
border: none; | |
border-radius: 4px; | |
cursor: pointer; | |
font-size: 16px; | |
} | |
button:hover { | |
background-color: #3700b3; | |
} | |
#output { | |
margin-top: 20px; | |
padding: 15px; | |
background: #e3f2fd; | |
border-radius: 4px; | |
white-space: pre-wrap; | |
display: none; | |
} | |
.error { | |
color: red; | |
font-weight: bold; | |
} | |
</style> | |
</head> | |
<body> | |
<div class="section"> | |
<h2>Сохранить текст в файл</h2> | |
<label for="saveFilePath">Имя файла (например, example.txt):</label> | |
<input type="text" id="saveFilePath" placeholder="example.txt" required> | |
<label for="content">Содержимое файла:</label> | |
<textarea id="content" required></textarea> | |
<button onclick="saveFile()">Сохранить</button> | |
</div> | |
<div class="section"> | |
<h2>Загрузить файл</h2> | |
<label for="uploadFile">Выберите файл:</label> | |
<input type="file" id="uploadFile"> | |
<button onclick="uploadFile()">Загрузить</button> | |
</div> | |
<div class="section"> | |
<h2>Прочитать файл</h2> | |
<label for="loadFilePath">Имя файла (например, example.txt):</label> | |
<input type="text" id="loadFilePath" placeholder="example.txt" required> | |
<button onclick="loadFile()">Прочитать</button> | |
<div id="output"></div> | |
</div> | |
<script> | |
async function saveFile() { | |
const filePath = document.getElementById('saveFilePath').value; | |
const content = document.getElementById('content').value; | |
const output = document.getElementById('output'); | |
if (!filePath || !content) { | |
output.textContent = 'Ошибка: Укажите имя файла и содержимое.'; | |
output.classList.add('error'); | |
output.style.display = 'block'; | |
return; | |
} | |
try { | |
const response = await fetch('/save-file', { | |
method: 'POST', | |
headers: { 'Content-Type': 'application/json' }, | |
body: JSON.stringify({ filePath, content }) | |
}); | |
const result = await response.json(); | |
if (response.ok) { | |
output.textContent = result.message; | |
output.classList.remove('error'); | |
} else { | |
output.textContent = `Ошибка: ${result.error}`; | |
output.classList.add('error'); | |
} | |
output.style.display = 'block'; | |
} catch (err) { | |
output.textContent = `Ошибка при сохранении файла: ${err.message}`; | |
output.classList.add('error'); | |
output.style.display = 'block'; | |
} | |
} | |
async function uploadFile() { | |
const fileInput = document.getElementById('uploadFile'); | |
const output = document.getElementById('output'); | |
if (!fileInput.files.length) { | |
output.textContent = 'Ошибка: Выберите файл.'; | |
output.classList.add('error'); | |
output.style.display = 'block'; | |
return; | |
} | |
const formData = new FormData(); | |
formData.append('file', fileInput.files[0]); | |
try { | |
const response = await fetch('/upload-file', { | |
method: 'POST', | |
body: formData | |
}); | |
const result = await response.json(); | |
if (response.ok) { | |
output.textContent = result.message; | |
output.classList.remove('error'); | |
} else { | |
output.textContent = `Ошибка: ${result.error}`; | |
output.classList.add('error'); | |
} | |
output.style.display = 'block'; | |
} catch (err) { | |
output.textContent = `Ошибка при загрузке файла: ${err.message}`; | |
output.classList.add('error'); | |
output.style.display = 'block'; | |
} | |
} | |
async function loadFile() { | |
const filePath = document.getElementById('loadFilePath').value; | |
const output = document.getElementById('output'); | |
if (!filePath) { | |
output.textContent = 'Ошибка: Укажите имя файла.'; | |
output.classList.add('error'); | |
output.style.display = 'block'; | |
return; | |
} | |
try { | |
const response = await fetch(`/load-file?filePath=${encodeURIComponent(filePath)}`); | |
const result = await response.json(); | |
if (response.ok) { | |
output.textContent = `Содержимое файла "${filePath}":\n${result.content}`; | |
output.classList.remove('error'); | |
} else { | |
output.textContent = `Ошибка: ${result.error}`; | |
output.classList.add('error'); | |
} | |
output.style.display = 'block'; | |
} catch (err) { | |
output.textContent = `Ошибка при чтении файла: ${err.message}`; | |
output.classList.add('error'); | |
output.style.display = 'block'; | |
} | |
} | |
</script> | |
</body> | |
</html> | |
=================================================================================================== | |
5. запустить сервер такой командой в терминале git bash: | |
node server.js | |
=================================================================================================== | |
6. зайти на http://localhost:3000/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment