Skip to content

Instantly share code, notes, and snippets.

@HuakunShen
Created December 10, 2022 06:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HuakunShen/1b77027b19f6fb2dc6386b942eff8b72 to your computer and use it in GitHub Desktop.
Save HuakunShen/1b77027b19f6fb2dc6386b942eff8b72 to your computer and use it in GitHub Desktop.
Read image as string -> convert back to buffer -> save image
import fs from 'node:fs';
const imagePath = '000000.jpg';
const encode = 'base64';
const rawImgBuf = fs.readFileSync(imagePath);
const encodedStr = rawImgBuf.toString(encode);
const recoveredBuf = Buffer.from(encodedStr, encode);
fs.writeFileSync('test.jpg', recoveredBuf);
// the other way: read as string directly
const base64Raw = fs.readFileSync(imagePath, {encoding: 'base64'});
fs.writeFileSync('test2.jpg', Buffer.from(base64Raw, 'base64'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment