1

I currently have an Angular app (MEAN Stack) that I am running locally on my Windows machine. Being new to Node/Express, I would like to be able to access a local directory from http://localhost:3006 that I have setup within my main app directory, called /myfiles which I am unsure how to do.

What I am unsure is, how do I create an endpoint to access and read these files from localhost within the /myfiles directory and display them within an Angular Material dialog?

Just not sure what I need to do as part of Express side (setting up the route) and then the Angular side (using HttpClient) to display.

Further to the above, I will also need to write back to the /myfiles directory, where I will need to perform a copy command based on a file selection within Angular.

halfer
  • 19,824
  • 17
  • 99
  • 186
tonyf
  • 34,479
  • 49
  • 157
  • 246

1 Answers1

1

You'll want to create an endpoint in Express that your Angular app can call to be served the files.

I'll assume the files you want to read and send are JSON files. Here's a really simple example of an endpoint that you can visit that will return the file to your frontend. In your Angular code you will make a get call to /myfile

var fs = require("fs");

app.get('/myFile', (req, res) => {
     var filepath = __dirname + '/myfiles/thefile.json';
     var file = fs.readFileSync(filepath, encoding);
     res.json(JSON.parse(file));
});

Then in Angular, you'll have something like

http.get('/myfile').subscribe( (data) => { console.log("The data is: ", data) });

ADDED

The example I provided above was just the basics to answer your question. Ideally, in production for file paths, you should the Node path library which 'knows' how to behave in different environments and file systems.

rayray
  • 1,625
  • 1
  • 9
  • 15
  • 1
    Thanks. Assuming that I will also need to deploy this app to a Linux environment, do I need to do anything different with the slashes? Further to your response, sorry but I've just updated my original post with regards to also writing back to the myfiles directory inorder to perform a copy. Are you able to please assist with this as well? Thanks. – tonyf Aug 20 '18 at 14:07