Nodejsでbase64エンコードされた画像を復元する

## 概要

↓のように、`img`タグの`src`がbase64エンコーディングされていた場合に、Nodejsでjpegなどの画像ファイルに変換する方法について記載してます。

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/203061/70d6b2e7-2573-89c4-171c-9350897be705.png)




## 解決したコード

* `data:image/jpeg;base64,`の部分を取り除く。
* `fs.writeFile`メソッドにエンコーディングを指定する。

```ts
import fs from "fs";

const base64Str = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBwgHBgkIBwgKCgkLDRYPDQwMDRsUFRAWIB0iIiAdHx8kKDQsJCYxJx8fLT0tMTU3Ojo6Iys/RD84QzQ5OjcBCgoKDQwNGg8PGjclHyU3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3N//AABEIAHAAcAMBIgACEQEDEQH/xAAcAAACAwEBAQEAAAAAAAAAAAAFBgIDBAEHAAj/xAA7EAACAQIEAggEAwgBBQAAAAABAgMEEQAFEiExQQYTIlFhcYGRFDKhsRUjwSRCYrLR4fDxUhYzcoKS/8QAGAEAAwEBAAAAAAAAAAAAAAAAAQIDAAT/xAAmEQACAgICAgEDBQAAAAAAAAAAAQIRAyESMRNRkQQiQRQyYYHw/9oADAMBAAIRAxEAPwBmyXOI0F+oipopE1HSgXQBq/ocXyZhBmcQCOWMb6gV2IYcL++NdB0VlYMKsKsd2W1uKm9vvjQ+WU+TRkwUs86tu5Eiki3mR9MRWOTVDSmls8/r4qz9gk0PrLyKVTgLsG3ty7eGfK5qCOCE1cSRzbBtiSdhc27t8Soo6itkqKX4KYMCZI22tcFOzcGw278aZ6SWllQTUCPc6iHkT7XNuWN+nlfQHnjXZPNCgnhaJgY5HIBP7oI07W5b39MBsvrZIK6RtJZXkI0gbldtPrvgpXUma5jTt1NLDGuvUhMliDv4eONmVZRSQ0yT1R01LsS6EhtJBNvS1sFYZ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hwsd7+5+oxurMvV9E6p1MsQJRhva24J8MZpGinSOuhuCyFezvtwIPkbjyIw12ha2US10NJVCGSR1I3Gnlfl4+2LnBuKhLyEDUhXfV3W7/APeJvDTVsMXWQk6eDlhq2++98a6eSlp0jgWeGMKLLqcH3++FtLobvs8n+Jakpg8hLOx7AYC/rgPraecytck8L92LcyqDNIW2twUd2KEPZsD7Y6LfHYkYrlaLSW78GqNx+GQBpEFw6nUTzPgDgIsd+ROCdK1OtEqy1AiYMezx+g88SlGyjdB2LNadd2k53No3O/rbGhelNNELItS7DmqKo+pOFoy0Q4PM58Et98QNTTA9lJj/AO2AsSQvJ/hDNL0vmdSEoWYEWPWzW/lAxjnzqWsSGkMVLDGuqRREp7J2tuTgGaxV+SEepxGGrVGlkkUlm+W3L+2G4IFyHag6QRw0ixVNQSRe4jgB535m2LX6VwrfSaqQ/wATqn8q/rhFav27KEeZxS9bKeAsPPA8YbY7SdLX36ujQ+Mru/3a30wObpbmT1EUWiFKZGJMYRQr7EWJtcccK3xU4JPZI8cZ7yf8z6YZQRnY5t0paMdijy5bfwM1vriodMK9W7L0cPcUhA/rhQ0niSx8zjmgd1sFQiamSkYPLtbSuwvjREl+Y9BjtJS2UO9hjWpiU6QQSOJxpSHhGkViMbagWPjwx1hvsotibNbicVPLbbURhBqINGx42xzRyJOO63PyKzeIGOaJydoyvmbYJqPtK34Y4dI4AeuPmR+DOg77YjoQfM5PlgikSQf3remInfgMXBU4KnqRi+KCdwAkW3eMbo1mNYnO4X1OLFhYntFR6YJR5TUyG5YKPHBCDIFteWUnwGFsHIBCGP8AeYt9MTiiUn8qLV6Xwzw5TSxi/VhvPGtIo02RFHpgNm5H/9k="
  .replace("data:image/jpeg;base64,","");

fs.promises.writeFile("test.jpeg", base64Str, { encoding: "base64" });
```