简体   繁体   中英

Access a local directory to retrieve files from localhost and write back

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM