Categories
JavaScript Answers

How to save a base64-encoded image to disk with Node.js?

Spread the love

Sometimes, we want to save a base64-encoded image to disk with Node.js.

In this article, we’ll look at how to save a base64-encoded image to disk with Node.js.

How to save a base64-encoded image to disk with Node.js?

To save a base64-encoded image to disk with Node.js, we can use the fs.writeFile method.

For instance, we write:

const base64Data = str.replace(/^data:image\/png;base64,/, "");

const fs = require("fs")

fs.writeFile("out.png", base64Data, 'base64', (err) => {
  console.log(err);
});

to remove the MIME type prefix from the base64 string with string replace.

Then we call fs.writeFile with the path to write the file to, the base64data string, the 'base64' encoding, and a callback that runs when writeFile is done.

If there’s an error, err will be set.

We need to pass in 'base64' to write the file as a base64 encoded file.

Conclusion

To save a base64-encoded image to disk with Node.js, we can use the fs.writeFile method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *