The Coder
The Coder

Reputation: 343

Sharp nodejs, axios input receiving undefined

Hey guys so basically I'm making an http request using axios to get an image as an "arraybuffer". After I receive the image I'm passing it to sharp but getting this error.

TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object. Received undefined

Here is my code

let res = await axios({ url, responseType: "arraybuffer" })
    
    const data = await sharp(res.data).resize({ width: 100, height: 100 }).toBuffer()
   
    const fileName = Md5.hashStr(entityId)
    requirements.Md5 = fileName
    requirements.fileName = fileName + fileExtension
    requirements.fileData = res.data
    return requirements;

For some reason sharp is saying I did not put an ArrayBuffer as input. But axios response seems to be type ArrayBuffer.

Any Ideas? Thanks

UPDATE/ANSWER So basically I just had to add one line

let res = await axios({ url, responseType: "arraybuffer" })
const buffer = Buffer.from(requirements.fileData, 'binary'); <---

const data = await sharp(res.data).resize({ width: 100, height: 100 }).toBuffer()

const fileName = Md5.hashStr(entityId)
requirements.Md5 = fileName
requirements.fileName = fileName + fileExtension
requirements.fileData = res.data
return requirements;

Upvotes: 2

Views: 1029

Answers (1)

The Coder
The Coder

Reputation: 343

UPDATE/ANSWER So basically I just had to add one line, transform my arraybuffer into binary did the trick

let res = await axios({ url, responseType: "arraybuffer" })
const buffer = Buffer.from(requirements.fileData, 'binary'); <---

const data = await sharp(res.data).resize({ width: 100, height: 100 }).toBuffer()

const fileName = Md5.hashStr(entityId)
requirements.Md5 = fileName
requirements.fileName = fileName + fileExtension
requirements.fileData = res.data
return requirements;

Upvotes: 1

Related Questions