Skip to content

Instantly share code, notes, and snippets.

@ahmadarif
Created February 8, 2019 09:33
Show Gist options
  • Save ahmadarif/f24cc4d1ab45d6d23a5c1e4161165d24 to your computer and use it in GitHub Desktop.
Save ahmadarif/f24cc4d1ab45d6d23a5c1e4161165d24 to your computer and use it in GitHub Desktop.
Get base64 from URI
'use strict'
const fs = require('fs')
const path = require('path')
const axios = require('axios')
const url = 'YOUR_IMAGE_URL'
async function base64FromUrl(url) {
const pathFile = path.resolve(__dirname, 'code.jpg')
const writer = fs.createWriteStream(pathFile)
const response = await axios({ url, method: 'GET', responseType: 'stream' })
response.data.pipe(writer)
return new Promise((resolve, reject) => {
writer.on('finish', () => {
resolve(fs.readFileSync(pathFile, 'base64'))
fs.unlinkSync(pathFile)
})
writer.on('error', reject)
})
}
async function imageencode() {
const base64 = await base64FromUrl(url)
console.log(base64)
}
imageencode()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment