使用nodejs的http和https下载远程资源
经常用到nodejs下载资源的情况(简单的爬虫),可以考虑直接使用nodejs内置的http/https模块。
test.mjs
import https from 'https'
import fs from 'fs'
https.get({
rejectUnauthorized: false, // 忽略https安全性
host: 'a.com', // 资源host|代理服务器
port: 443, // 资源端口|代理服务器端口
method: 'GET', // 请求方式
path: '/xx.jpg', // 资源地址:https://a.com/xx.jpg
headers: {
referer: '', // 如果资源有防盗链,则清空该属性
},
}, res => {
//设置编码格式
res.setEncoding('binary');
let img = ''
res.on('data', chunk => {
img += chunk
})
res.on('end', chunk => {
// 写到本地,(文件名,源文件,编码格式)
fs.writeFileSync('./test.jpg', img, "binary");
})
})