@sophons/request
Version:
🚀 Probably the best Node.js HTTP request component, It also contains a rich stream processing
67 lines (66 loc) • 2.69 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.fastDownload = exports.fastGetString = exports.fastGetStream = exports.fastGetBuffer = void 0;
const fs = require("fs");
const axios_1 = require("axios");
/**
* Based on the URL corresponding to the resource transform to buffer
*/
exports.fastGetBuffer = (url, configs) => __awaiter(void 0, void 0, void 0, function* () {
if (!url)
return null;
const response = yield axios_1.default(Object.assign({ url, responseType: 'arraybuffer' }, configs));
return response.data;
});
/**
* Based on the URL corresponding to the resource transform to stream
*/
exports.fastGetStream = (url, configs) => __awaiter(void 0, void 0, void 0, function* () {
if (!url)
return null;
const response = yield axios_1.default(Object.assign({ url, responseType: 'stream' }, configs));
return response.data;
});
/**
* Based on the URL corresponding to the resource transform to a string in the specified format
*/
exports.fastGetString = (url, type = 'base64', configs) => __awaiter(void 0, void 0, void 0, function* () {
if (!url)
return null;
const buffer = yield exports.fastGetBuffer(url, configs);
return buffer.toString(type);
});
/**
* Based on the URL download file
*/
exports.fastDownload = (url, path, configs, isStream = false) => __awaiter(void 0, void 0, void 0, function* () {
if (!url || !path)
return null;
/**
* Write stream
*/
if (isStream) {
const stream = yield exports.fastGetStream(url, configs);
yield new Promise((resolve, reject) => {
const writeStream = stream.pipe(fs.createWriteStream(path));
writeStream.on('error', (error) => reject(error));
writeStream.on('finish', () => resolve(null));
});
}
/**
* Write buffer
*/
else {
fs.writeFileSync(path, yield exports.fastGetBuffer(url, configs), 'binary');
}
return path;
});