const https = require('https');
const fs = require('fs');
const path = require('path');
const { URL } = require('url');
async function downloadFile(url, outputPath) {
// Парсим URL для получения компонентов
const parsedUrl = new URL(url);
// Если путь для сохранения не указан, используем имя файла из URL
if (!outputPath) {
outputPath = path.basename(parsedUrl.pathname);
}
return new Promise((resolve, reject) => {
const file = fs.createWriteStream(outputPath);
https.get(url, (response) => {
// Проверяем статус код ответа
if (response.statusCode !== 200) {
reject(new Error(`Ошибка загрузки: ${response.statusCode}`));
return;
}
// Получаем общий размер файла для прогресса
const totalSize = parseInt(response.headers['content-length'], 10);
let downloadedSize = 0;
response.pipe(file);
// Опционально: отслеживание прогресса загрузки
response.on('data', (chunk) => {
downloadedSize += chunk.length;
if (totalSize) {
const percent = (downloadedSize / totalSize * 100).toFixed(2);
console.log(`Загружено: ${percent}%`);
}
});
file.on('finish', () => {
file.close();
resolve({ path: outputPath, size: downloadedSize });
});
}).on('error', (err) => {
fs.unlink(outputPath, () => reject(err));
});
file.on('error', (err) => {
fs.unlink(outputPath, () => reject(err));
});
});
}
// Пример использования
downloadFile('https://example.com/file.zip', './downloaded-file.zip')
.then((result) => console.log(`Файл сохранен: ${result.path} (${result.size} байт)`))
.catch((err) => console.error('Ошибка загрузки:', err));
const app = express()
app.enable('view cache')
app.set('view cache', false)
process.env.NODE_ENV = 'development'
$.post("/index", {
name: "ТЕСТ",
designation: "FN_TAST",
}, function( data ) { // передаем и загружаем данные с сервера с помощью HTTP запроса методом POST
$( "div" ).html( data ); // вставляем в элемент <div> данные, полученные от сервера
});
async function fnOne() {
return new Promise(res=>setTimeout(()=>{res(1000)}, 1000))
}
async function fnTwo() {
return new Promise(res=>setTimeout(()=>{res(2000)}, 1200))
}
async function fnThree() {
return new Promise(res=>setTimeout(()=>{res(3000)}, 1400))
}
const allFn = async ()=>{
try {
await fnOne()
console.log('Выполнилась 1-я ф-ция')
const rz = await fnTwo()
console.log('Выполнилась 2-я ф-ция, полученный результат = ', rz)
await fnThree()
console.log('Выполнилась 3-я ф-ция')
}catch (e) {
console.error(e)
}
}
allFn()
npm i axios
const axios = require('axios'); // или импорт если es6 настроен
let uploadFileForm = new FormData()
uploadFileForm.append('file', fs.createReadStream(data.file))
// делаешь запрос
axios.post(data.url, uploadFileForm, { headers: form.getHeaders() })
.then(function (response) { // смотрим в консоли на результат
console.log(response.data);
console.log(response.status);
console.log(response.statusText);
console.log(response.headers);
console.log(response.config);
})
.catch(console.log (error)) // или ошибку