As a front-end image cutout, I often do some image compression, the most commonly used is tinyPng. However, only 20 pictures can be uploaded and compressed at a time on the web page, which is cumbersome to operate, and it is also a troublesome thing to save after compression.

So suddenly there is a program that uses NodeJS to simplify these operations. After going to Baidu and knowing that tinyPNG has an API, the next step is to make your own money.

The preparatory work

  • The node version 12.19.0
  • Apply for tinify KEY
  • Install Tinify NPM install –save Tinify official documentation

Write a program

Generate the corresponding folder to save the image

const {
    statSync,
    readdirSync,
    readFileSync,
    mkdirSync,
    mkdir,
    rmdirSync,
    rmdir,
    writeFileSync,
    writeFile
} = require('fs')
const {
    resolve
} = require('path')
const colors = require('colors-console')
const DIR_NAME = resolve(__dirname, 'images') // Uncompressed storage address
const NEW_DIR_NAME = resolve(__dirname, 'new_images') // Compressed image address
/ * * * *@param {String} Path uncompressed address *@param {String} NewFilePath Compressed image address */
const compress = (path, newFilePath) = > {
    const files = readdirSync(path) // Read the file directory
    if (files.length > 0) {
        files.map(item= > {
            let filePath = resolve(path, item) // File/folder address
            let newPath = resolve(newFilePath, item) // Address of the file/folder to save
            let stats = statSync(filePath) // Get the file/folder description
            if (stats.isDirectory()) { // If it is a folder
                console.group(colors('cyan'.` folder${item}Information `));
                console.log(colors('cyan'.'This is a folder, the address is${filePath}`));
                console.log(colors('cyan'.The new address is:${newPath}`));
                console.groupEnd();
                rmdir(newPath, { // Delete the file first to avoid errors and block when creating existing files
                    recursive: true // Setting this property to delete will traverse the entire folder
                }, () = > {
                    mkdir(newPath, (err) = > {// Create a folder
                        if (err) throw err
                        console.log(colors('green'.'Created successfully:${newPath}`))
                        compress(filePath, newPath) // Continue to iterate through the folder to create the full directory})})}})}}Copy the code

Handle file

const tinify = require("tinify");
tinify.key = 'your key'
const compress = (path, newFilePath) = > {
    const files = readdirSync(path) // Read the file directory
    if (files.length > 0) {
        files.map(item= > {
            let filePath = resolve(path, item) // File/folder address
            let newPath = resolve(newFilePath, item) // Address of the file/folder to save
            let stats = statSync(filePath) // Get the file/folder description
            if (stats.isDirectory()) { // If it is a folder
                console.group(colors('cyan'.` folder${item}Information `));
                console.log(colors('cyan'.'This is a folder, the address is${filePath}`));
                console.log(colors('cyan'.The new address is:${newPath}`));
                console.groupEnd();
                rmdir(newPath, { // Delete the file first to avoid errors and block when creating existing files
                    recursive: true // Setting this property to delete will traverse the entire folder
                }, () = > {
                    mkdir(newPath, (err) = > {// Create a folder
                        if (err) throw err
                        console.log(colors('green'.'Created successfully:${newPath}`))
                        compress(filePath, newPath) // Continue to iterate through the folder to create the full directory})})}})}else if (stats.isFile()) { // If it is a file
                console.group(colors('blue'.` file${item}Information `));
                console.log(colors('blue'.'This is a file at the address${filePath}`));
                console.groupEnd();
                // tinyPNG supports only JPG and PNG formats
                let itemSplit = item.split('. ')
                if (itemSplit[1]! = ='jpg' && itemSplit[1]! = ='png' && itemSplit[1]! = ='jpeg') { 
                    console.log(colors('red'.The current file format is${itemSplit[1]}, only supports compressed JPG, PNG, JPEG and so on! `));
                    return
                }
                const sourceData = readFileSync(filePath)
                tinify.fromBuffer(sourceData).toBuffer(function (err, resultData) {
                    if (err) throw err;
                    writeFile(newPath, resultData, (err) = > {
                        if (err) throw err;
                        console.log(colors('yellow'.'Compressed and saved successfully:${newPath}`)); }); }); }}Copy the code

The complete code

const {
    statSync,
    readdirSync,
    readFileSync,
    mkdirSync,
    mkdir,
    rmdirSync,
    rmdir,
    writeFileSync,
    writeFile
} = require('fs')
const {
    resolve
} = require('path')
const colors = require('colors-console')
const tinify = require("tinify");
tinify.key = 'your key'
const DIR_NAME = resolve(__dirname, 'images') // Uncompressed storage address
const NEW_DIR_NAME = resolve(__dirname, 'new_images') // Compressed image address
/ * * * *@param {String} Path uncompressed address *@param {String} NewFilePath Compressed image address */
const compress = (path, newFilePath) = > {
    const files = readdirSync(path) // Read the file directory
    if (files.length > 0) {
        files.map(item= > {
            let filePath = resolve(path, item) // File/folder address
            let newPath = resolve(newFilePath, item) // Address of the file/folder to save
            let stats = statSync(filePath) // Get the file/folder description
            if (stats.isDirectory()) { // If it is a folder
                console.group(colors('cyan'.` folder${item}Information `));
                console.log(colors('cyan'.'This is a folder, the address is${filePath}`));
                console.log(colors('cyan'.The new address is:${newPath}`));
                console.groupEnd();
                rmdir(newPath, { // Delete the file first to avoid errors and block when creating existing files
                    recursive: true // Setting this property to delete will traverse the entire folder
                }, () = > {
                    mkdir(newPath, (err) = > {// Create a folder
                        if (err) throw err
                        console.log(colors('green'.'Created successfully:${newPath}`))
                        compress(filePath, newPath)  // Continue to iterate through the folder to create the full directory})})}else if (stats.isFile()) { // If it is a file
                console.group(colors('blue'.` file${item}Information `));
                console.log(colors('blue'.'This is a file at the address${filePath}`));
                console.groupEnd();
                / / because
                let itemSplit = item.split('. ')
                if (itemSplit[1]! = ='jpg' && itemSplit[1]! = ='png' && itemSplit[1]! = ='jpeg') { 
                    console.log(colors('red'.The current file format is${itemSplit[1]}, only supports compressed JPG, PNG, JPEG and so on! `));
                    return
                }
                const sourceData = readFileSync(filePath)
                tinify.fromBuffer(sourceData).toBuffer(function (err, resultData) {
                    if (err) throw err;
                    writeFile(newPath, resultData, (err) = > {
                        if (err) throw err;
                        console.log(colors('yellow'.'Compressed and saved successfully:${newPath}`));
                    });
                });
            }
        })
    }
}
compress(DIR_NAME, NEW_DIR_NAME)
Copy the code

!!!!!!!!! End and spend

First article, I hope you can give me more advice