使用nodeJS的request下载图片
- 下载依赖包
npm install request --save
- Code
let fs = require('fs'); let request = require('request'); function downloadImage(url, filePath) { return new Promise((resolve, reject) => { try { var stream = fs.createWriteStream(filePath); request(url).pipe(stream).on("close", () => { stream.close(); resolve(true); }); } catch (error) { console.log(error); reject(error); } }); } function download() { var url = "http://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png"; var filePath = "D:/img/baidulogo.png"; downloadImage(url, filePath).then(() => { console.log("Download success"); }, (err) => { console.log(err); }).then(undefined, err => { console.log(err); }) } download();
使用nodeJS的http下载
- Code
let fs = require('fs'); let http = require('http'); function downloadImage(url, filePath) { let req_option = { url: url, method: "GET", rejectUnauthorized: false, headers: { 'Content-Type': 'application/octect-stream' } }; if (fs.existsSync(filePath)) { fs.unlinkSync(filePath); } return new Promise((resolve, reject) => { http.get(url, req_option, (msg) => { msg.on("data", (data) => { fs.writeFileSync(filePath, data, { flag: "a" }); }).on("error", (err) => { reject(err); }).on("end", () => { resolve(true); }); }).on('error', function (err) { Logger.error(__filename, `Download file error, ${err}`); reject(err); }); }); } function download() { var url = "http://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png"; var filePath = "D:/img/baidulogo.png"; downloadImage(url, filePath).then(() => { console.log("Download success"); }, (err) => { console.log(err); }).then(undefined, err => { console.log(err); }) } download();