这里的压缩是借助了 tinify 的 api 来是实现的 也可以引入本地压缩的库来实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#!/usr/bin/env node

const path = require('path')
const fs = require('fs')
const tinify = require('tinify');
const ora = require('ora')

tinify.key = 'rv72TV007SJ82jpJCjsPhR5jk0RgNPdn';

const CWD_PATH = process.cwd()
const USER_PATH = process.argv[2] || './'
const IMG_PATH = path.join(CWD_PATH, USER_PATH)
const extList = ['.png', '.jpg']

// 解析目录
function readdir(dirPath) {
const spinner = ora('目录解析中...').start();
try {
const files = fs.readdirSync(dirPath)
if (files.length === 0) {
throw new Error('没有可用的文件')
}
const list = files.filter(i => extList.includes(path.extname(i)) && fs.statSync(path.join(dirPath, i)).isFile())
if (list.length === 0) {
throw new Error('没有可用的图片文件,当前仅支持对 .png .jpg 的文件进行压缩')
}
spinner.succeed(`目录解析成功,共${list.length}个文件需要压缩`)
return list
} catch (error) {
spinner.fail(`目录解析失败`)
throw new Error(error.message)
}
}

// 压缩图片
function compress(filePath) {
const file = path.basename(filePath)
const spinner = ora(`${file}压缩中...`).start();

return new Promise((resolve) => {
tinify.fromFile(filePath).toFile(filePath).then(res => {
spinner.succeed(`${file}压缩完成`)
resolve()
}).catch(err => {
spinner.fail(`${file}压缩失败`)
console.log(err)
resolve()
})
})
}

// 检查当前目录或者文件是否存在
function check(path) {
const spinner = ora('检查目录中').start();
try {
const result = fs.statSync(path)
spinner.succeed('检查完成')
return result
} catch (error) {
spinner.fail('目录不可用')
throw new Error(path + ' 路径异常')
}
}

async function start() {
try {
const checkResult = check(IMG_PATH)
if (checkResult.isDirectory()) {
const files = readdir(IMG_PATH)

for (let i = 0; i < files.length; i++) {
try {
compress(path.join(IMG_PATH, files[i]))
} catch (error) {
console.log('error', error)
}
}
} else {
if (!extList.includes(path.extname(IMG_PATH))) {
console.log('这不是一个图片文件,当前仅支持对 .png .jpg 的文件进行压缩')
return
}
compress(IMG_PATH)
}
} catch (error) {
console.log(error.message)
}
}

start()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
{
"name": "@my-utils/tinify",
"version": "1.0.1",
"description": "this is a node shell",
"author": "winnerwly<winnerwly@gmail.com>",
"main": "index.js",
"bin": {
"tinify": "./index.js"
},
"repository": {
"type": "git",
"url": "https://github.com/my-utils/tinify"
},
"homepage": "https://github.com/my-utils/tinify/",
"publishConfig": {
"access": "public"
},
"license": "ISC",
"dependencies": {
"ora": "^5.4.1",
"tinify": "^1.6.1"
}
}
  • bin 用来声明命令行工具的名称 工具的名称可以跟 npm 包的名称不一致
  • publishConfig.access 声明包未 公共包 非付费用户需要添加
  • ora 用来实现 命令行加载效果
  • tinify 用来调用tinify服务 实现图片压缩

获取工具

1
npm install -g @my-utils/tinify

使用工具

1
tinify

tinify 后面可以使用相对路径或者文件名称

相关信息

tinypng官网
ora文档
tinify文档