How to get the Axios's response file type All In One
How to get the Axios's response file type All In One
获取 Axios 请求响应头中的文件类型
Axios API
https://www.npmjs.com/package/axios
demos
import fs from 'node:fs';
import path from 'path';
import axios from 'axios';
async function downloadFile(url, path) {
const writer = fs.createWriteStream(path);
const res = await axios({
url,
method: "GET",
responseType: "stream",
});
// console.log(`res =`, res)
console.log(`✅ content-type =`, res.headers['content-type'])
res.data.pipe(writer);
return new Promise((resolve, reject) => {
writer.on("finish", resolve);
writer.on("error", reject);
});
}
const url = `https://cdn.xgqfrms.xyz/video/web-testing.mp4`
await downloadFile(url, "./test.mp4");
// ✅ content-type = video/mp4
/*
$ node ./file-type.js
*/
import axios from 'axios';
async function getUser() {
try {
const response = await axios.get(
'https://api.xgqfrms.xyz/api/users',
);
console.log(response.headers);
console.log(response.headers['date']);
console.log(response.headers['etag']);
console.log(response.headers['connection']);
console.log(response.headers['content-type']);
return response.data;
} catch (err) {
console.log(err);
}
}
console.log(await getUser());
(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!
web crawler
downloader
import axios from 'axios';
// import axios, {isCancel, AxiosError} from 'axios';
// import fs from 'node:fs';
import {createWriteStream} from 'node:fs';
// import path from 'path';
// import { fileURLToPath } from 'url';
// const __filename = fileURLToPath(import.meta.url);
// const __dirname = path.dirname(__filename);
// console.log(`import.meta.url`, import.meta.url)
// console.log(`__dirname`, __dirname)
// async function downloadFile(url, path) {
// const res = await axios({
// url,
// method: "GET",
// responseType: "stream",
// });
// console.log(`✅ content-type =`, res.headers['content-type'])
// res.data.pipe(createWriteStream(path));
// }
async function downloadFile(url, path) {
await axios({
url,
method: "GET",
responseType: "stream",
}).then(res => {
console.log(`✅ content-type =`, res.headers['content-type'])
return res.data.pipe(createWriteStream(path));
}).catch(err => {
console.log(`❌ err =`, err)
}).finally(() => {
console.log(`finally 👻`)
})
}
// const url = `https://edu-vod.lagou.com/sv/2daa3bb9-1765150ee6e/2daa3bb9-1765150ee6e.mp4`
const url = `https://cdn.xgqfrms.xyz/video/web-testing.mp4`
await downloadFile(url, "./test.mp4");
/*
$ node ./axios.js
*/
refs
https://byby.dev/node-download-image
https://bobbyhadz.com/blog/axios-get-response-headers
https://stackoverflow.com/questions/63742908/downloading-video-image-etc-from-url/76975697#76975697
©xgqfrms 2012-2021
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/17657447.html
未经授权禁止转载,违者必究!