node.jsdownloadfilesystemsnode-modulesnodejs-stream

I have created one node js file to list out all files in my file system , When I am trying to download file its size is changed in node js


When I try to download a file, its size changes in a node js file that I have developed to list out all of the files in my file system. enter image description here

This is my sample Code :

   const filePath = path.join(directoryPath, fileName);
        if (fs.existsSync(filePath)) {
            const fileExtension = path.extname(fileName);
            let fileType = mime.contentType(fileExtension);
            const HEADER = { 'Content-Type': fileType, 'Content-Disposition': 'attachment; filename=' + fileName };
            const textFile = fs.readFileSync(filePath, 'utf8');
            res.writeHead(200, HEADER);
            res.end(textFile);
        } else {
            res.writeHead(404, HEADER);
            res.end("File not found");
        }
    }

this is the link to my complete code : https://github.com/msrajawat298/myserver.git

when I am trying to download the .iso file its size goes to change the old size of iso is 200MB and it will after downloading 364.38 MB similarly I am getting the same issue is all these given extensions File extensions List deb, sqlite. bz2, xml.gz, db, gz, box, repo,img, msg,cfg,c32,xsl,iso. It is working fine when I am trying to download the file with extensions of txt, cmd, jpg, png, bin, XML, and html, not getting issues with these extensions.

Sample Output link : https://myserver.mayankkushwah.repl.co/


Solution

  • This is the changes I have done to resolve the issue.

    if (fileName !== '') {
      const filePath = path.join(directoryPath, fileName);
      if (fs.existsSync(filePath)) {
        const fileExtension = path.extname(fileName);
        let fileType = mime.contentType(fileExtension);
        const HEADER = { 'Content-Type': fileType, 'Content-Disposition': 'attachment; filename=' + fileName };
        const fileStream = fs.createReadStream(filePath);
        res.writeHead(200, HEADER);
        fileStream.pipe(res);
      } else {
        res.writeHead(404, HEADER);
        res.end("File not found");
      }
    }
    

    I have updated the code in my GitHub repo anyone wants they access it from this link: https://github.com/msrajawat298/myserver