Cannot read property 'pipe' of undefined in node js

Viewed 6341

I'm trying to download image using axios and fs When i run it using node app.js it gives me an error saying pipe can't be defined

"TypeError: Cannot read property 'pipe' of undefined".

const axios = require('axios');
const fs = require('fs');
const Path = require('path');


async function download()
{
    const url ='https://www.google.co.in/imgres'
    const path = Path.resolve(__dirname,'files','image1.jpg')

    const response = axios
    (
        {
        method : 'GET',
        url:url,

        responseType:'stream'
        }
    )

    response.data.pipe(fs.createWriteStream(path))
        return new Promise((resolve,reject)=>{
            response.data.on('end',()=>{
            resolve()
        })

        response.data.on('error',err=>{
            reject(err);
        })
    }).catch();
}

download().then(()=>{
    console.log('download finished');
})
1 Answers

Don't you need to wait for axios promise to complete?

See Axios API

...
    const response = axios
    (
        {
        method : 'GET',
        url:url,

        responseType:'stream'
        }
    ).then(function(response) {

        response.data.pipe(fs.createWriteStream(path))
            return new Promise((resolve,reject)=>{
                response.data.on('end',()=>{
                resolve()
            })
...

Depending on script level you could do this with async/await too I guess, but I'm no Axios expert.

Related