JS 常用的一些功能性函数

常用的一些功能性函数

关于原生JS

16进制转rgb()或rgba()字符串

const hexToRgb = (hexT, opacity) => {
  const rgb = [];
  let hex = hexT.toString(16);
  hex = hex.substr(1); //去除前缀 # 号

  if (hex.length === 3) {
    // 处理 "#abc" 成 "#aabbcc"
    hex = hex.replace(/(.)/g, "$1$1");
  }
  hex.replace(/../g, function(color) {
    rgb.push(parseInt(color, 0x10)); //按16进制将字符串转换为数字
  });
  const color = rgb.join(",");
  return typeof opacity === "number" ? `rgba( ${color} , ${opacity} )` : `rgb( ${color} )`;
};

文件大小单位转换

/**
 * @desc bytesToSize 字节单位换算
 * @param bytes 传入以bit为单位的数据
 */
const bytesToSize = function (bytes) {
    const k = 1024;
    if (!bytes || bytes === 0) return '0 B';
    if (typeof (bytes) == 'string') {
        return bytes
    } else {
        const byte = Math.abs(bytes); //正负数均变正数
        const sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
        const i = Math.floor(Math.log(byte) / Math.log(k));
        return (byte / Math.pow(k, i)).toFixed(2) + sizes[i];
    } 
}

时间转换

/**
 * 时间格式化
 * @param {date} time 传入的时间戳 | 时间
 * @param {string} type 返回的格式化时间
 */
function formatDate(timer, type = 'YMDHMS', bar = '-') {
  if (!timer) return ''
  let date = timer ? new Date(timer) : new Date()
  let Y = date.getFullYear()
  let M = zero(date.getMonth() + 1)
  let D = zero(date.getDate())
  let h = zero(date.getHours())
  let m = zero(date.getMinutes())
  let s = zero(date.getSeconds())
  const TIME_NOW = {
    YM: Y + bar + M,
    YMD: Y + bar + M + bar + D,
    YMDHMS: Y + bar + M + bar + D + ' ' + h + ':' + m + ':' + s,
    HMS: h + ':' + m + ':' + s
  }
  return type ? TIME_NOW[type] : TIME_NOW
  function zero(date) {
    return date < 10 ? '0' + date : date
  }
}

解析URL后的参数并转换为对象

/**
 * @param {string} url
 * @returns {Object}
 */
export function parseURL(url) {
  const search = url.split("?")[1];
  if (!search) {
    return {};
  }
  return JSON.parse(
    '{"' +
      decodeURIComponent(search)
        .replace(/"/g, '\\"')
        .replace(/&/g, '","')
        .replace(/=/g, '":"')
        .replace(/\+/g, " ") +
      '"}'
  );
}

生成随机数

/**
 * @returns {string}
 */
export function createUniqueString() {
  const timestamp = +new Date() + "";
  const randomNum = parseInt((1 + Math.random()) * 65536) + "";
  return (+(randomNum + timestamp)).toString(32);
}
/**
 * @returns {string}
 */
export function createUniqueString2() {
const R = () => (((date.getTime() + Math.random()) * 0x100000) | 0).toString(16).substring(1)
    const sessionId = 'sessionId-' + date.getMinutes() + R() + '-' + date.getSeconds() + R() + '-' + date.getMilliseconds() + R() + '-|' + R()
  return sessionId;
}

关于Vue

增加图片健壮性自定义指令

//检测图片是否存在
const imgIsExist = url =>
  new Promise(resolve => {
    var img = new Image();
    img.onload = function() {
      if (this.complete === true) {
        resolve(true);
        img = null;
      }
    };
    img.onerror = function() {
      resolve(false);
      img = null;
    };
    img.src = url;
  });

    // 用于判断当前图片是否能够加载成功,可以加载成功则赋值为img的src属性,否则使用默认图片
Vue.directive('realImg',    async (el, binding) {
      let imgURL = binding.value; //获取图片地址
      let defaultURL = el.getAttribute("default-img"); //获取默认图片地址
      if (!imgURL) return false;
      let exist = await imgIsExist(imgURL);
      if (exist) {
        el.setAttribute("src", imgURL);
      } else if (defaultURL) {
        el.setAttribute("src", defaultURL);
      }
    })

// 使用

 <img
   v-realImg="actual-url"
   :src="default-img"
   :default-img="default-img"
 />

关于 axios

接收二进制流文件乱码问题。

1. 须将axios 配置中的responseType设置为'arraybuffer',这样就不会让表格出现乱码现象;
2. 如果要动态设置文件名则需要让后台将名字设置到响应头中,否则将是一个乱码的文件名;
3. 然后通过<a></a> 标签的特性来,自动点击下载文件;
4. 如果要兼容IE则需要利用navigator.msSaveOrOpenBlob方法;
5. 兼容Firefox 须将<a></a> 标签添加到body中,最后再移除<a></a> 标签

// axios config
 config = {
     responseType: 'arraybuffer'
    }

// 返回数据处理
getUserInfoExport(data).then(({data,headers}) => {
        let blob = new Blob([data], { type: 'application/vnd.ms-excel' }) // 将服务端返回的文件流(二进制)excel文件转化为blob
        let fileName = headers.filename

        if (window.navigator && window.navigator.msSaveOrOpenBlob) { // IE10+
          window.navigator.msSaveOrOpenBlob(blob, fileName)
        } else {
          let objectUrl = (window.URL || window.webkitURL).createObjectURL(blob)
          let downFile = document.createElement('a')
          downFile.style.display = 'none'
          downFile.href = objectUrl
          downFile.download = fileName // 下载后文件名
          document.body.appendChild(downFile)
          downFile.click()
          document.body.removeChild(downFile) // 下载完成移除元素
          // window.location.href = objectUrl
          window.URL.revokeObjectURL(objectUrl) // 只要映射存在,Blob就不能进行垃圾回收,因此一旦不再需要引用,就必须小心撤销URL,释放掉blob对象。
        }
      })

参考连接

关于 Node

获取本机 IP 地址

const os = require('os');
const ip = showObj(os.networkInterfaces());

function showObj(obj){
/*     for (let devName in obj){
        let iface = obj[devName];
        for (let i = 0;i < iface.length;i++){
            let alias = iface[i];
            if (alias.family === 'IPv4'
                && alias.address !== '127.0.0.1'
                && !alias.internal){
                return alias.address;
            }
        }
    } */
     for (let devName in obj){
             let iface = obj[devName];
             for (let alias of iface ){
                if ( alias.family === 'IPv4'  && alias.address !== '127.0.0.1'  && !alias.internal) return alias.address;
             }
     }
}
posted @ 2020-05-29 23:54  G_Owen  阅读(547)  评论(0编辑  收藏  举报