Home » excel » Node.js – How do I export Excel files to client/UI which are already available in a folder?

Node.js – How do I export Excel files to client/UI which are already available in a folder?

Posted by: admin May 14, 2020 Leave a comment

Questions:

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.

How to&Answers:

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});
})