Home > Software engineering >  get image with fetch api and save through fs module
get image with fetch api and save through fs module

Time:12-19

With this function i can download any files that contains text. but i also want to download images like .png and .jpg how to do that using fetch

async function fetchGithubFileContent(url) {
    let res = await fetch(url).then((res) => res.text())
    window.electronAPI.writeFile({ content: res, fileName: "res.js" })
}

async function writeFile({ content, fileName }) {
    fs.writeFile(path.join(__dirname, fileName), content, () => console.log(`successfully saved ${fileName}`))
}

fetchGithubFileContent("https://raw.githubusercontent.com/Tetrax-10/Nord-Spotify/master/src/nord.js")

If we cant do it with fetch is it possible with axios? then how?

CodePudding user response:

Am answering my own ques as i solved it after a hour.

import { Buffer } from "buffer"

async function writeFile({ content, fileName }) {
    fs.writeFile(path.join(__dirname, fileName), content, () => console.log(`successfully saved ${fileName}`))
}

async function writeImage({ binaryData, fileName }) {
    let formatedBinaryData = binaryData.replace(/^data:image\/\w ;base64,/, "")
    let buffer = Buffer.from(formatedBinaryData, "base64")
    await writeFile({ content: buffer, fileName: fileName })
}

async function imageUrlToBase64(url) {
    let response = await fetch(url)
    let blob = await response.blob()
    return new Promise((onSuccess, one rror) => {
        try {
            const reader = new FileReader()
            reader.onload = function () {
                onSuccess(this.result)
            }
            reader.readAsDataURL(blob)
        } catch (error) {
            one rror(error)
        }
    })
}

async function downloadGithubImage(url) {
    let base64 = await imageUrlToBase64(url)
    let fileName = url.split("/").pop()
    window.electronAPI.writeImage({ binaryData: base64, fileName: fileName })
}

downloadGithubImage("https://raw.githubusercontent.com/Tetrax-10/Spicetify-Themes/master/assets/home.png")

CodePudding user response:

Another method is by using node streams (better method)

import https from "https"
const { pipeline } = require("stream/promises")
import path from "path"
import fs from "fs"

async function download(url) {
    return new Promise(async (onSuccess) => {
        https.get(url, async (res) => {
            let fileName = url.split("/").pop()
            const fileWriteStream = fs.createWriteStream(path.join(__dirname, fileName), {
                autoClose: true,
                flags: "w",
            })
            await pipeline(res, fileWriteStream)
            onSuccess("success")
        })
    })
}

await download("https://raw.githubusercontent.com/Tetrax-10/Spicetify-Themes/master/assets/artist-2.png")
  • Related