Sorting out the use of some functional functions

Keywords: Javascript axios Vue Excel JSON

Some commonly used functional functions

About native JS

File size unit conversion

/**
 * @desc bytesToSize Byte unit conversion
 * @param bytes Incoming data in 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); //Positive and negative all positive
        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];
    } 
}

Resolve parameters after URL and convert to object

/**
 * @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, " ") +
      '"}'
  );
}

Generate random number

/**
 * @returns {string}
 */
export function createUniqueString() {
  const timestamp = +new Date() + "";
  const randomNum = parseInt((1 + Math.random()) * 65536) + "";
  return (+(randomNum + timestamp)).toString(32);
}


About Vue

Add image robustness custom instruction

//Check whether the picture exists
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;
  });

    // Used to determine whether the current picture can be loaded successfully. If it can be loaded successfully, it will be assigned to the src attribute of img. Otherwise, the default picture will be used
Vue.directive('realImg',    async (el, binding) {
      let imgURL = binding.value; //Get picture address
      let defaultURL = el.getAttribute("default-img"); //Get default image address
      if (!imgURL) return false;
      let exist = await imgIsExist(imgURL);
      if (exist) {
        el.setAttribute("src", imgURL);
      } else if (defaultURL) {
        el.setAttribute("src", defaultURL);
      }
    })

// use

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

About axios

Receiving binary stream file is in disorder.

1. The responseType in the axios configuration must be set to 'arraybuffer', so that the table will not be scrambled;
2. If you want to set the file name dynamically, you need to let the background set the name to the response header, otherwise it will be a garbled file name;
3. Then click the download file automatically through the < a > < a > tag feature;
4. If you want to be compatible with IE, you need to use navigator.msSaveOrOpenBlob method;
5. For Firefox compatibility, you must add the < a > < a > tag to the body, and then remove the < a > < a > tag

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

// Return data processing
getUserInfoExport(data).then(({data,headers}) => {
        let blob = new Blob([data], { type: 'application/vnd.ms-excel' }) // Convert the file stream (binary) excel file returned by the server to 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 // File name after download
          document.body.appendChild(downFile)
          downFile.click()
          document.body.removeChild(downFile) // Download complete remove element
          // window.location.href = objectUrl
          window.URL.revokeObjectURL(objectUrl) // As long as the mapping exists, blobs cannot be garbage collected, so once the reference is no longer needed, you must carefully undo the URL and release the blob object.
        }
      })

Reference connection

About Node

Get local IP address

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 by gilijk on Sat, 30 May 2020 08:29:56 -0700