先写清它要回答什么
我有个脚本专门列出草稿中体积最大的图片,按从大到小打印尺寸和路径。起因是文件夹里有一堆相似的文件名,我连续两次换错了图。几个月后再回来,我也能马上想起脚本要回答的问题。
让输出方便复核
我一直用字节计算大小,直到显示结果时才格式化。文件同样大时,用文件名确定顺序。这样第二次运行很好比较。脚本只是读取和报告,也方便交给不了解目录结构的人使用。
import { readdir, stat } from 'node:fs/promises';
import { join } from 'node:path';
const folder = process.argv[2] ?? 'public/assets';
const images = (await readdir(folder, { withFileTypes: true }))
.filter((entry) => entry.isFile() && /\.(svg|webp|png|jpe?g|avif)$/i.test(entry.name));
const files = await Promise.all(images.map(async ({ name }) => {
const path = join(folder, name);
return { path, bytes: (await stat(path)).size };
}));
files.sort((a, b) => b.bytes - a.bytes || a.path.localeCompare(b.path));
for (const { path, bytes } of files) console.log(bytes, path);
留一条能重新上手的路
如果某个命令会写文件,我会先让它列出将要发生的改动,再保证重复运行也能得到预期结果。我还会把一条实际可运行的示例放在脚本旁边。从项目根目录执行它,要能找到真实目录,也要能看懂输出。