js websocket 二进制与文本的转换

废话不多说,直接上代码

/**
 * Blob转文本
 * @param {Blob} blob 原始Blob数据
 * @param {string} type 要转换的类型,默认为Text
 * @returns {Promise<unknown>}
 */
async function blob2Text(blob, type) {
    return new Promise(resolve => {
        const r = new FileReader();
        r.onloadend = function () {
            resolve(r.result);
        }
        try {
            r['readAs' + (type || "Text")](blob);
        } catch (e) {
            console.log("Error:", e);
        }
    });
}

/**
 * 文本转Blob
 * @param {string} text 文本内容
 * @returns {Blob}
 */
function text2Blob(text) {
    return new Blob([new Int16Array(0), text]);
}
posted @ 2021-11-22 10:11  凭栏知潇雨  阅读(816)  评论(0编辑  收藏  举报