Skip to content
nodejs下载文件到本地
js
const https = require('http');
const fs = require('fs');
const path = require('path');

function downloadFile(url, outputPath) {
    return new Promise((resolve, reject) => {
        const file = fs.createWriteStream(outputPath);

        https.get(url, (response) => {
            if (response.statusCode !== 200) {
                reject(new Error(`请求失败,状态码:${response.statusCode}`));
                return;
            }

            response.pipe(file);

            file.on('finish', () => {
                console.log('下载完成');
                file.close();
                resolve();
            });
        }).on('error', (err) => {
            console.error('下载失败:', err.message);
            fs.unlink(outputPath, () => { }); // 删除不完整文件
            reject(err);
        });
    });
}

// 使用
downloadFile(
    'http://43.143.149.30:8006/my-download/jrttquantxt/23章_穷白垃圾.txt',
    path.join(__dirname, '1.txt')
).then(() => {
    console.log('下载完成');
}).catch(console.error);