2

I have a folder which contains all my Excel Sheets which are built using the npm package excel4node.

Now I want to export these files to users dependent on the name of files.

How do I do that?

I've tried referencing this post although I don't understand how to export those files to the user.

Erik Cederstrand
  • 9,643
  • 8
  • 39
  • 63
Abhay Bh
  • 139
  • 1
  • 4
  • 16
  • what do you mean by users, do you want to send it to the client? – damitj07 Apr 03 '18 at 05:21
  • Yes, I want to send it to the Client – Abhay Bh Apr 03 '18 at 05:31
  • ok , Please post some code you have tried to send them to client. – damitj07 Apr 03 '18 at 05:37
  • I have tried [this code](https://stackoverflow.com/a/2727191/7854532). However, it is only able to list all files in console or on the browser. I want to list all excel sheets to my Clients so that they can directly download them. I want to do something like [Bootstrap Listr](https://idleberg.com/demo/Bootstrap-Listr-2/), but in either plain html5 or in node.js – Abhay Bh Apr 03 '18 at 05:46
  • did you try this answer as well? https://stackoverflow.com/a/25580289/7889129 – Maddy Apr 03 '18 at 05:58

1 Answers1

3

If I got your question right, you want to send an excel file when a client makes an API call with possibly a username. To do so here is some pseudo code :

app.get('/user/:username', function(req, res) {
  const username = req.params['username'];
  const filePath =  "/path/to/"+username+".excel" 

  // Check if file specified by the filePath exists 
  fs.exists(filePath, function(exists){
       if (exists) {     
         //send the file to client
         res.sendFile(filePath);
       }
    });
})

note* res.sendFile() is supported by Express v4.8.0 onwards.


Now as per your comments if you want to send a list of all files to the client you will have to return an array of strings and render it on the UI.

app.get('/user/all', function(req, res) {

  const testFolder =  "/path/to/folder";

  // read the folder and set the result in a variable    
  var listOfFiles = fs.readdirSync(testFolder);
  // send a JSON or any other response with these strings
  res.json({"allFiles" : listOfFiles});
})
damitj07
  • 2,689
  • 1
  • 21
  • 40
  • 1
    @damjit07 , thank you for the revert. Your answer is working perfectly when coupled with my app. However, it is working only in `server.js` file. When I try to use the same code in other file and use router to route the incoming request to that file, then it gives me [this error](https://stackoverflow.com/questions/39492259/enoent-no-such-file-or-directory-stat-error-with-express-middleware) – Abhay Bh Apr 03 '18 at 06:51
  • I guess the issue will be with the relative path of your folder and code file – damitj07 Apr 03 '18 at 10:47
  • Yes. Its a path issue. Anyways, thank you for the answer. – Abhay Bh Apr 03 '18 at 10:49