获取url指定参数
function QueryString(val) {
var uri = window.location.search;
var re = new RegExp("[?&]" + val + "=([^&?]*)", "ig");
return ((uri.match(re)) ? (uri.match(re)[0].substr(val.length + 2)) : null)
}
获取url所有参数
function getQueryObject(url) {
url = url == null ? window.location.href : url
const search = url.substring(url.lastIndexOf('?') + 1)
const obj = {}
const reg = /([^?&=]+)=([^?&=]*)/g
search.replace(reg, (rs, $1, $2) => {
const name = decodeURIComponent($1)
let val = decodeURIComponent($2)
val = String(val)
obj[name] = val
return rs
})
return obj
}
查询数组中指定元素下标
function findArray(array, feature, all = true) {
for (const index in array) {
const cur = array[index];
if (feature instanceof Object) {
let allRight = true;
for (const key in feature) {
const value = feature[key];
if (cur[key] === value && !all) return array[index];
if (all && cur[key] !== value) {
allRight = false;
break;
}
}
if (allRight) return array[index];
} else {
if (cur === feature) {
return array[index];
}
}
}
return null;
}
获取昨天
function getYesterDate(time) {
const date = time ? new Date(time) : new Date();
date.setTime(date.getTime() - 24 * 60 * 60 * 1000);
return date;
}
判断对象数组中是否存在指定键值对
function arrayIsExistKeyValue(arr, key, value) {
if (arr.length > 0) {
return arr.some(item => item[key] === value);
}
return false;
}
网络文件下载
'use strict';
const ProgressBar = require('progress');
const https = require('https');
const http = require('http');
const fs = require('fs');
const Path = require('path');
const URL = require('url');
/**
* 下载单个文件
* @param {String} fileUrl 网络文件路径
* @param {String} path 文件存放位置
* @param {String} fileName 文件名
*/
const downloadFile = (fileUrl, path, fileName) => {
fileName = fileName ? fileName : Path.basename(fileUrl);
path = path ? path : './';
const stream = fs.createWriteStream(path + fileName);
const url = URL.parse(fileUrl);
let req = null;
if (url.protocol === 'http:') req = http.request(url);
if (url.protocol === 'https:') req = https.request(url);
req.on('response', (res) => {
const len = parseInt(res.headers['content-length'], 10);
const bar = new ProgressBar(`downloading ${fileName} [:bar] :rate/bps size: ${len}KB :percent :etas`, {
complete: '=',
incomplete: '-',
width: 100,
total: len,
})
res.on('data', chunk => {
bar.tick(chunk);
stream.write(chunk, 'utf-8');
})
res.on('end', _ => {
console.log('/n')
stream.end();
})
res.on('error', err => {
console.error(err);
})
})
req.end();
}
/**
* 下载多个文件
* @param {String[]} fileUrls 网络文件路径数组
* @param {String} path 文件存放位置
*/
const downloadFiles = (fileUrls, path) => {
if (fileUrls && fileUrls.length === 0) throw new Error('fileUrls cannot be empty');
path = path ? path : './';
fileUrls.forEach(url => {
downloadFile(url, path)
})
}
module.exports = {
downloadFile,
downloadFiles,
}