Skip to content

常用工具函数

复制内容到剪切板

js
navigator.clipboard.writeText(content)

获取鼠标选中的内容

js
window.getSelection().toString()

随机打乱数组

js
array => array.sort(() => Math.random() - 0.5)

颜色格式转换

rgb转16进制

js
[r, g, b].map(num => parseInt(num).toString(16).padStart(2, '0')).join('')

16进制换rgb

js
const hexToRgba = hex => {
  const [r, g, b] = hex.match(/\w\w/g).map(val => parseInt(val, 16))
  return `rgba(${r}, ${g}, ${b}, 1)`;
}

获取文件夹文件结构

定义

js
import path from 'path';
import fs from 'fs';
function getAllFile(dir) {
    let filesNameArr = [];
    function readdirs(dir) {
        let result = {
            text: path.basename(dir),
            children: [],
        };
        fs.readdirSync(dir).forEach((file) => {
            let subPath = path.join(dir, file);
            let stats = fs.statSync(subPath);
            if (stats.isDirectory()) {
                result.children.push(readdirs(subPath));
            } else if (stats.isFile() && file.endsWith('.md')) {
                result.children.push(subPath);
            }
        });
        return result;
    }
    filesNameArr.push(readdirs(dir));
    return filesNameArr;
}

用法

js
const dirPath = path.join(__dirname, '../pages/');
const files = getAllFile(dirPath);