使用nodeJS下载图片

const http = require('http');
const https = require("https");
const cheerio = require('cheerio');
const request = require('request');
const fs = require('fs');

function filterData(data) {
    const $ = cheerio.load(data);
    let textLi = '';
    $('.goods-list-wrap .gl-item img.item-pic').each((index, el) => {
        let imgurl = $(el).attr('data-original');
        console.log($(el).attr('data-original'))
        textLi += $(el).attr('data-original') + "\n";
        console.log(imgurl.split('/')[imgurl.split('/').length - 1], 'fhg')
        let fileName = "./img/" + imgurl.split('/')[imgurl.split('/').length - 1];
        download_img('https:' + imgurl, fileName)
    })
    console.log($('#title-category').text(), 'text')
    fs.writeFile(`${$('#title-category').text()}.txt`, textLi, (err) => {
            if (err) throw err;
            console.log('文本文件已创建并写入数据');
        })
        // console.log(data);
}

// 下载图片
function download_img(img_url, file_name) {
    request(img_url).pipe(fs.createWriteStream(file_name)).on('close', function() {
        console.log('pic saved!')
    })
}
const server = http.createServer((req, res) => {
    let data = "";
    https.get("https://lists.meizu.com/page/list?categoryid=76", (result) => {
        result.on("data", (chuck) => {
            data += chuck;
        })

        result.on("end", () => {
            filterData(data);
        })
    })
})


server.listen(8080, () => {
    console.log("locallhost:8080")
})

你可能感兴趣的:(nodeJS)