getBuffer.js

"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const https_1 = __importDefault(require("https"));
const http_1 = __importDefault(require("http"));
const fs_1 = __importDefault(require("fs"));
const streamToBuffer_1 = __importDefault(require("./streamToBuffer"));
/**
 * 获取本地或远程文件 buffer
 *
 * @since 0.0.1
 * @param input 本地或远程文件地址
 * @returns buffer 对象
 * @example
 *
 * const buf1 = await getBuffer('./text.txt');
 * const buf2 = await getBuffer('some url or image');
 *
 */
function getBuffer(input) {
    return new Promise((resolve, reject) => {
        if (typeof input !== 'string') {
            if (Buffer.isBuffer(input)) {
                resolve(input);
            }
            else {
                reject(new TypeError('参数错误'));
            }
            return;
        }
        // http 或 https 图片地址
        const client = input.indexOf('https') === 0 ? https_1.default : input.indexOf('http') === 0 ? http_1.default : undefined;
        if (client) {
            client.get(input, (res) => {
                const chunks = [];
                res.on('error', reject);
                res.on('data', (chunk) => chunks.push(chunk));
                res.on('end', () => {
                    resolve(Buffer.concat(chunks));
                });
            });
        }
        else {
            // 本地路径
            const stream = fs_1.default.createReadStream(input);
            (0, streamToBuffer_1.default)(stream).then(resolve).catch(reject);
        }
    });
}
exports.default = getBuffer;