1

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

1 Answers1

1

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.

Abraham Labkovsky
  • 1,771
  • 6
  • 12
  • i went to download file at front-end side . so how can i do ?? – Jeet Shekhaliya Apr 28 '22 at 11:22
  • You can test your server by making an HTTP request from any client. You can use a cli tool like `curl` or an app like Postman. If the response is what you expect it to be, kindly mark the question as answered. If you have a front end question, dig a bit and see if someone else has asked it and perhaps an answer is already available. If not, submit a new question... – Abraham Labkovsky Apr 28 '22 at 16:37