Node download method produces empty file

。_饼干妹妹 提交于 2020-01-06 08:09:50

问题


To practice my node I am trying to make a file downloader. The aim is to get a url of a file from a database (currently mp3), download it to the project and use it as an href on the client side.

I have managed to get the promises working and a file downloads, however the file is saying it's empty, but when I go into the project, I can open the file(mp3) fine.

Here is what I have so far:

    .then(() => {
        Promise.resolve()
          .then(() => {
            return new Promise(resolve => {
              console.log("Started download");

              // req.body.total_source is the full url of the file
              console.log(req.body.total_source);

              setTimeout(() => {
                download(req.body.total_source, "dist").then(() => {
                  console.log("downloaded!");
                  resolve();
                });
              }, 1000);
            });
          })
          .then(() => {
            console.log("success page rendered");
            res.render("success", {

              // only get file name from url
              song_link: req.body.total_source.substring(
                req.body.total_source.lastIndexOf("/") + 1,
                req.body.total_source.length
              ),

              song_source: req.body.total_source,
              name: req.body.name
            });
          });
      })

And the button is set up as (using ejs):

<a href="/dist/<%= song_link %>"  download>Download <%= name %></a>

Can anyone point me in the right direction? The console.logs all show that the download is finished before the success page is rendered, so i'm not sure why it says "Failed - empty file".


回答1:


FIXED: I think the problem was that I was saving the file to the dist folder, when I had setup the project to use client assets from a 'public' folder. Saving the files to "/public/assets" fixed to problem:

download(req.body.total_source, "public/assets");


来源:https://stackoverflow.com/questions/54982960/node-download-method-produces-empty-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!