KAKAMU
BlogTag

ディレクトリ内の画像を再帰的にwebpに変換する

そもそも

Node.jsでディレクトリ内の画像を再帰的にwebpに変換するスクリプト。

主な依存パッケージ

// node v20.x
"devDependencies": {
    "sharp": "0.33.5"
}

main.js

main.js
const fs = require('fs')
const path = require('path')
const sharp = require('sharp')
 
function convertExtentionToWebp(fileName) {
  return fileName.replace(/\.[^/.]+$/, '.webp')
}
 
async function convertSingleFileToWebp(dirPath, file) {
  if (file.match(/\.(jpg|jpeg|png)$/)) {
    const s = sharp(`${dirPath}/${file}`)
      // https://sharp.pixelplumbing.com/api-output#withmetadata
      .withMetadata()
      // https://sharp.pixelplumbing.com/api-operation#rotate
      .rotate()
      // https://sharp.pixelplumbing.com/api-output#webp
      .webp({ lossless: false })
    // https://sharp.pixelplumbing.com/api-output#tofile
    await s.toFile(path.join(dirPath, convertExtentionToWebp(file)))
    fs.rmSync(path.join(dirPath, file))
    console.log('--------------------')
    console.log(
      `"${file}" has been converted to "${convertExtentionToWebp(file)}".`,
    )
  }
}
 
async function convertDirRecursivelyToWebp(dirPath) {
  const items = fs.readdirSync(dirPath).filter((item) => item !== '.DS_Store')
  for (let i = 0; i < items.length; i++) {
    const item = items[i]
    if (fs.lstatSync(path.join(dirPath, item)).isDirectory()) {
      await convertDirRecursivelyToWebp(path.join(dirPath, item))
    } else {
      await convertSingleFileToWebp(dirPath, item)
    }
  }
  console.log('========================================')
  console.log(`All files under "${dirPath}" have been converted to webp`)
}
 
const dirPath = process.argv[2]
if (!dirPath) {
  console.error('Specify Directory Path!')
  process.exit(1)
}
 
convertDirRecursivelyToWebp(dirPath)

参考リンク

Node.js file stats

#IT#Node.js#自動化