一)axios(arraybuffer) 【推荐姿势】
const fs = require('fs')
const axios = require('axios')
function downloadFile(url,localPath){
axios.get(url,{responseType: "arraybuffer"})
.then(async function (response) {
const bufObj = Buffer.from(await response.data);
fs.writeFileSync(localPath,bufObj,'binary')
});
}
二)https(node自带) 【推荐姿势】
const https = require('node:https')
const fs = require('fs')
function downloadFile(url,localPath){
https.get(url, (res) => {
var imgData = "";
res.setEncoding("binary"); // 下载图片需要设置为 binary, 否则图片会打不开
res.on('data', (chunk) => {
imgData+=chunk;
});
res.on('end', () => {
fs.writeFileSync(localPath, imgData, "binary");
});
});
}
三)其他姿势
xior
官网 https://github.com/suhaotian/xior
import xior from 'xior';
const axios = xior.create();
axios
.get('https://bit.ly/2mTM3nY', {
responseType: 'stream',
})
.then(async function ({ response, config }) {
const buffer = Buffer.from(await response.arrayBuffer());
return writeFile('ada_lovelace.jpg', buffer);
});
got
官网 https://github.com/sindresorhus/got
import got from 'got'
function downloadFile(url,localPath){
got.stream(url).pipe(fs.createWriteStream(localPath))
}
四)axios(stream)【不推荐】
let config = {
adapter: "http",
};
function downloadOneFile(url, target, onSuccess, onError) {
axios.create(config).get(url, {
responseType: 'stream'
}).then(response => {
const writer = createWriteStream(target);
response.data.pipe(writer);
writer.on('finish', onSuccess);
writer.on('error', onError);
}).catch(onError);
}
这个使用姿势,我这里碰到几个问题:
- 要使用 stream,就得使用pipe 输出 。 时常会有出现
data.pipe is not a function
. 没了解到原因,不知道为啥。 - 在electron 环境中使用, 需要设置 adapter 为http(默认为 xhr)。 但我设置了 adapter为http后。又有问题:
Adapter 'http' is not available in the build
。 github问题单 ,目前单子还是open的,没解决。
网友评论