const http = require('http')
const fs = require('fs')

module.exports.httpDownload = (uri, dest) => {
    return new Promise((resolve, reject) => {
        // 确保dest路径存在
        const writeStream = fs.createWriteStream(dest)

        console.debug(`download start: ${uri}`)
        http.get(uri, (res) => {
            if (res.statusCode !== 200) {
                reject({ message: `Http请求失败 (Status Code = ${res.statusCode})` })
                return
            }

            res.on('end', () => {
                console.debug('download end')
            })

            // 进度、超时等
            writeStream.on('finish', () => {
                console.debug('finish write file')
                resolve()
            }).on('error', (error) => {
                fs.unlinkSync(dest)
                reject(error)
            })

            res.pipe(writeStream)
        }).on('error', reject)
    })
}

//httpDownload('http://s3.pstatp.com/toutiao/xitu_juejin_web/img/logo.a7995ad.svg', './xxx.svg');
