Search code examples
javascriptnode.jsgoogle-drive-apifs

How to download a file with Node.js from google drive api


How to download a file with Node.js from google drive api

I don't need anything special. I only want to download a file from a GoogleDrive, and then save it to a given directory of client.

app.get("/download",function(req,res){

  const p38290token = new google.auth.OAuth2(CLIENT_ID, CLIENT_SECRET, REDIRECT_URI);
    p38290token.setCredentials({ refresh_token: token.acc });
    const p38290Id = google.drive({
        version: "v3",
        auth: p38290token,
    });
    var dest = fs.createWriteStream("./test.png");
    try {
        p38290Id.files.get({
                fileId: "1daaxy0ymKbMro-e-JnexmGvM4WzW-3Hn",
                alt: "media"
            }, { responseType: "stream" },
            (err, res) => {
                res.data
                    .on("end", () => {
                        console.log("Done");
                    })
                    .on("error", err => {
                        console.log("Error", err);
                    })
               .pipe(dest); // i want to sent this file to client who request to "/download"
            }
        )
    } catch (error) {

    }

})

I want to do that just someone come to www.xyz.com/download and file will be download automatically


Solution

  • The issue seems to be with this line:

    var dest = fs.createWriteStream("./test.png");
    

    You are using a file system command which is meant to interact with files on the server. Your question makes it clear that you wish for express to deliver the contents of the file over to the client making the HTTP request.

    For that you can just use the res parameter of the route callback function. You declare it on this line:

    app.get("/download",function(req,res){
    
    

    In your case I'd remove the dest variable completely and simply pipe the file to res like so:

    .pipe(dest);
    

    Have a look at this answer as well.